我剛開始學習C++,並且一直在使用float和double值。下面是兩個代碼片段,這些代碼片段似乎在做同樣的事情,但會給出不同的結果。我錯過了什麼?有人可以解釋第一個代碼必須得到與第二個代碼不同的結果的精度錯誤。爲什麼這兩個代碼片段會產生不同的結果? (浮點數,雙精度)
int _tmain(int argc, _TCHAR* argv[])
{
const float f = 0.1;
const double d = 0.1;
int counter = 0;
for(counter; ((double)counter * f - (double)counter * d) < 0.34; counter++) {}
cout << "Iterations = " << counter << "\n" ;
system("pause");
return 0;
}
int main (int argc, const char * argv[])
{
float time_f = 0.1;
double time_d = 0.1;
float total_f = 0;
double total_d = 0;
int count=0;
double difference = 0;
while (true) {
total_d = count * time_d;
total_f = count * time_f;
if(total_f - total_d >= 0.34){
break;
}
count++;
}
std::cout << count << "\n";
system("pause");
}
我已經改變了我對float和double但價值沒有區別之間循環條件的演員。
推薦閱讀:http://floating-point-gui.de/ –
http://docs.oracle.com/cd/E19957- 01/806-3568/ncg_goldberg.html –