[英]I am not sure why my code is producing this arithmetic error?
Hey everybody I am working on a program in c that tells you the least number of coins needed for any given amount of money. 嘿,我正在研究c中的一个程序,告诉你任何给定金额所需的硬币数量最少。 I have a program written that works for for every amount I have tested except for $4.20. 我有一个程序编写,适用于我测试的每个金额,除了4.20美元。
Here is my code: 这是我的代码:
#include <cs50.h>
#include <stdio.h>
#include <math.h>
int main(void)
{
float f;
int n, x, y, z, q, s, d, t;
do {
printf("How much change do you need?\n");
f = GetFloat();
} while(f <= 0);
{
n = (f * 100);
}
q = (n / 25);
x = (n % 25);
y = (x / 10);
z = (x % 10);
s = (z / 5);
d = (z % 5);
t = (q + y + s + d);
{
printf("%d\n" ,t);
}
}
The strange thing is when I input 4.20 the output is 22 instead of 18 (16 quarters and 2 dimes). 奇怪的是当我输入4.20输出是22而不是18(16宿舍和2角钱)。 I did some sleuthing and found that the problem is with my variable x. 我做了一些调查,发现问题出在我的变量x上。 When I input 4.2, x gives me 19 and not 20 like it should. 当我输入4.2时,x给我19而不是20。 I tried other cases that I thought should have produced the same problem like 5.2 and 1.2 but it worked correctly in those cases. 我尝试了其他我认为应该产生相同问题的案例,如5.2和1.2,但它在这些情况下正常工作。 It might be a rounding issue but I would think that same error would also happen with those similar values. 这可能是一个舍入问题,但我认为同样的错误也会发生在那些相似的值上。
Does anyone have an idea about why this might be happening? 有没有人知道为什么会这样?
PS I am fairly new to coding and I haven't gotten much formal instruction so I also welcome tips on better indentation and formatting if you see anything obvious. PS我对编码很新,我还没有得到很多正式的指导,所以如果你看到任何明显的东西,我也欢迎有关更好的缩进和格式化的提示。
IEEE 754 floating point is often slightly imprecise, and casting will truncate, not round. IEEE 754浮点通常略微不精确,并且转换将截断,而不是圆形。 What's likely happening is that 4.20 * 100
evaluates to 419.999999999999994
(exact number is immaterial, point is, it's not quite 420), and the conversion to int
drops the decimal portion, producing 419. 可能发生的是4.20 * 100
评估为419.999999999999994
(确切数字是无关紧要的,点是,它不是420),转换为int
会丢弃小数部分,产生419。
The simple approach is to just do: 简单的方法就是:
n = f * 100 + 0.5;
or you can use a proper function: 或者您可以使用适当的功能:
n = round(f * 100);
If the number is "almost" exact, either one will be fine, you'd only get discrepancies when someone passed non-integer cents ( "4.195"
or the like), and if you're using float
for monetary values, you've already accepted precision issues in the margins; 如果数字“几乎”精确,任何一个"4.195"
,只有当有人通过非整数美分( "4.195"
之类)时才会出现差异,而如果你使用float
货币价值,你就是'我们已经接受了边际的精确度问题; if you want exact numbers, you'd use the decimal
formats that have fixed precision for decimal values, and are intended for financial calculations. 如果你想要精确的数字,你可以使用十进制值具有固定精度的decimal
格式,并用于财务计算。
Try this: Provides up to 2 digit precision. 试试这个:提供高达2位数的精度。
//float f
double f
f *= 1000;
f = floor(f); /* optional */
f /= 10;
f = floor(f); /* optional */
n = f;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.