【发布时间】:2012-01-25 11:02:03
【问题描述】:
我才刚刚开始学习 C++,并且一直在搞乱浮点和双精度值。下面是两个代码 sn-ps,在我看来它们在做同样的事情但给出不同的结果。我错过了什么?有人可以解释第一个代码必须得到与第二个不同的结果所必须的精度错误吗?
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 之间更改了 for 循环条件的转换,但值没有不同。
【问题讨论】:
标签: c++ floating-point double precision