[問題] 指數加了轉型後取ceil()結果不同
問題(Question):
不懂為什麼把2強制轉型結果會不同,以及使用不同std結果不同
預期的正確結果(Expected Output):
2
2
錯誤結果(Wrong Output):
使用xcode 6.2
2
3
使用$ c++ -o test_ceil test_ceil.cpp
2
2
使用$ c++ -std=c++11 -o test_ceil test_ceil.cpp
2
3
gcc version 4.8.2 (Ubuntu 4.8.2-19ubuntu1)
程式碼(Code):(請善用置底文網頁, 記得排版)
#include <iostream>
#include <cmath>
using namespace std;
int main(int argc, char *argv[]) {
float r1 = sqrt(pow(3,2)-pow(2,2));
cout << ceil(sqrt(pow(r1,(float)2)-pow(1,2))) << endl;// <---2
cout << ceil(sqrt(pow(r1,2)-pow(1,2))) << endl;// <---3
}
補充說明(Supplement):
如果把sqrt(pow(r1,(float)2)和sqrt(pow(r1,2)單獨用float存出來再放回最後
兩式的話三種編譯環境出來結果都會是2,2
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 118.167.85.113
※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1426685867.A.E00.html
推
03/18 21:59, , 1F
03/18 21:59, 1F
→
03/18 22:00, , 2F
03/18 22:00, 2F
推
03/18 22:02, , 3F
03/18 22:02, 3F
→
03/18 22:09, , 4F
03/18 22:09, 4F
推
03/18 22:30, , 5F
03/18 22:30, 5F
→
03/18 22:31, , 6F
03/18 22:31, 6F
請問什麼是模擬兩可的覆載呢?
※ 編輯: yea107 (118.167.85.113), 03/18/2015 22:41:28
→
03/18 22:58, , 7F
03/18 22:58, 7F
→
03/18 22:58, , 8F
03/18 22:58, 8F
→
03/18 22:59, , 9F
03/18 22:59, 9F
→
03/18 23:00, , 10F
03/18 23:00, 10F
→
03/18 23:07, , 11F
03/18 23:07, 11F
推
03/19 02:15, , 12F
03/19 02:15, 12F
→
03/19 02:16, , 13F
03/19 02:16, 13F
→
03/19 02:17, , 14F
03/19 02:17, 14F
→
03/19 02:17, , 15F
03/19 02:17, 15F
喔喔,所以在pow(r1,(float)2)會選到pow(float,float),
而pow(r1,2)會選到pow(double,double) !!
非常感謝!!
我還以為第二種狀況他會把2轉成float然後叫pow(float,float)...
※ 編輯: yea107 (118.167.85.113), 03/19/2015 03:15:56
推
03/19 03:21, , 16F
03/19 03:21, 16F
推
03/19 21:59, , 17F
03/19 21:59, 17F
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章