简体   繁体   English

printf() 是否修改其参数?

[英]Does printf() modify its parameters?

I was trying to see how different languages handle floating point numbers.我试图了解不同的语言如何处理浮点数。 I know that there are some inherent issues in floating point representation, which is why if you do 0.3 + 0.6 in Python, you get 0.899999 and not 0.9我知道浮点表示存在一些固有的问题,这就是为什么如果你在 Python 中做 0.3 + 0.6,你会得到 0.899999 而不是 0.9

However, these snippets of code simply left me astounded:然而,这些代码片段让我震惊:

double x = 0.1,
    sum = 0;

for(int i=0; i<10; ++i) 
    sum += x;

printf("%.9lf\n",sum);
assert(sum == 1.0);

The above snippet works fine.上面的代码片段工作正常。 It prints 1.0.它打印 1.0。 However, the following snippet gives a runtime error due the assertion failing:但是,由于断言失败,以下代码段给出了运行时错误:

double x = 0.1,
    sum = 0;

for(int i=0; i<10; ++i) 
    sum += x;

assert(sum == 1.0);
printf("%.9lf\n",sum);

The only change in the two snippets above is the order of the assert and printf statements.上面两个片段中唯一的变化是 assert 和 printf 语句的顺序。 This leads me to think that printf is somehow modifying its arguments and rounding them off somehow.这让我认为 printf 正在以某种方式修改其参数并以某种方式将它们四舍五入。

Can someone please throw some light on this?有人可以对此有所了解吗?

Some processors, such as x86, have floating point registers that are higher precision than the data type (80 bit, compared to 64 bit for a double).某些处理器,例如 x86,具有比数据类型精度更高的浮点寄存器(80 位,而双精度则为 64 位)。 Calling printf() causes these registers to be stored on the stack, where there is only 64 bits allocated for the variable.调用 printf() 会使这些寄存器存储在堆栈中,其中只有 64 位分配给变量。 This causes the difference you are observing.这会导致您观察到的差异。

For more information see What every computer scientist should know about floating-point arithmetic.有关更多信息,请参阅 每个计算机科学家应该了解的有关浮点运算的知识。

printf() does not modify its parameters. printf()不修改其参数。

I can't imagine asking help for an error and not stating what error you are getting.我无法想象向错误寻求帮助而不是说明您遇到了什么错误。 Do you mean it asserts.你的意思是它断言。 Are you sure that both don't assert, but you only see the one that asserts before the printf() for some reason?您确定两者都没有断言,但出于某种原因,您只能看到在printf()之前断言的那个吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM