简体   繁体   English

为什么我的代码返回的数字比应返回的数字小?

[英]Why is my code returning a number lower than what it should return?

So I am doing an assignment for a programming course and I am having trouble with one line of my code. 因此,我正在为编程课程做作业,而我的一行代码遇到了麻烦。

the answer should be (if my math is correct) 40 but the program returns 39. 答案应该是(如果我的数学正确的话)40,但程序返回39。

example: 18.33 * 40 *52 = 38126.4 例如:18.33 * 40 * 52 = 38126.4

I then use this code 然后我使用此代码

double wage = 0;
wage = wage * 40 * 52;
wage = wage - floor(wage);
wage = wage * 100;
printf(" %d cents", (int)wage);

But the program returns 39. If I don't change it to int it is 40.0000000 但是程序返回39。如果我不将其更改为int,则为40.0000000

What is happening? 怎么了?

Floating point numbers are incapable of representing every real number to infinite precision. 浮点数无法以无限精度表示每个实数。 And 40.0 is no exception. 40.0也不例外。 Instead, if your calculation is done in a correct and numerically stable way, you'll get the closest number a double can represent. 相反,如果您以正确且数值稳定的方式进行计算,则会获得double精度数可以代表的最接近的数字。

Functions like printf make the output pretty by considering how close the operand they received is to a given number. 诸如printf之类的printf通过考虑它们接收到的操作数与给定数字的接近程度使输出漂亮。

So your result may be 39.99998 , the closest number a double can represent to your correct result. 因此,您的结果可能是39.99998 ,即double 39.99998代表正确结果的最接近数字。 And it is shown as 40.0000000 . 它显示为40.0000000

However casting to an int performs truncation. 但是强制转换为int会执行截断。 So it becomes 39 . 这样就变成了39

For your purposes (you seem to be dealing in money), an approach which will work best is to get rid of floating point numbers completely. 为了您的目的(您似乎在赚钱),一种最有效的方法是完全消除浮点数。 You only need two integers. 您只需要两个整数。 One for cents (which grows only up to 100), and one for dollars 1 . 一分钱(最多只能增长100分),一分钱1美元。

1 I assume dollars and cents because of the multiplication by 100 in your code. 1我假设美元和美分是因为您的代码中乘以100 Naturally it applies for any currency 自然,它适用于任何货币

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

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