gpt4 book ai didi

c++ - 为什么这两个代码片段会产生不同的结果? ( float , double )

转载 作者:行者123 更新时间:2023-11-28 01:00:34 26 4
gpt4 key购买 nike

我才刚刚开始学习 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 之间更改了我的 for 循环条件的转换,但值没有不同。

最佳答案

floatdouble 都有一个有限的表示,这意味着它们具有一系列离散值,而不仅仅是任何实际值。在特别是,在您的示例中,0.1 没有精确的 float 我所知道的任何现代机器上的表示(所有这些机器都使用一个基数在他们的实现中是 2 的幂——0.11/5 *
1/2
1/5 的倍数不能有有限表示,除非基数是 5 的倍数)。

结果是 floatdouble 具有相同的底层表示(通常不是这种情况),否则会有差异一旦 count 不为 0。

这个主题的通常引用是“什么每个计算机科学家都应该了解 float 算术”。直到您阅读并理解(或至少理解其中的含义)它,你不应该触摸漂浮的机器点。

关于c++ - 为什么这两个代码片段会产生不同的结果? ( float , double ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9001598/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com