non*_*eah 3 c double int casting formula
我试图截断超过百分之十的小数.(13.4396将是13.43)不是总是或从不工作?
我有这个99%的公式:
input = (( (double) ((int)(orgInput * 100)) ) / 100) ;
Run Code Online (Sandbox Code Playgroud)
然后我有这个算术等价的公式序列:
input = (orgInput * 100);
input = (int) input;
input = (double) (input);
input = input / 100;
Run Code Online (Sandbox Code Playgroud)
这些输入不会产生所需的结果(公式截断并向下舍入,而细分步骤输出所需的结果):
12.33
99.99
22.22
44.32
56.78
11.11
然后对我来说更大的一个谜团是为什么33.30对它们中的任何一个都不起作用.以下是我的程序,它不断运行以证明我的问题.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
double orgInput, input;
while (4!=3)
{
printf("Please enter the dollar amount (up to $100) => ");
scanf("%lf", &orgInput);
/* Truncates anything past hundredths place */
input = (orgInput * 100) ;
printf("\n1. input is %g \n ", input);
input = (int) input ;
printf("\n2. input is %g \n ", input);
input = (double) (input) ;
printf("\n3. input is %g \n", input);
input = input / 100 ;
printf("\n4. input is %.2lf \n", input);
input = (( (double) ((int)(orgInput * 100)) ) / 100) ;
printf("\nUsing the formula the input is %.2lf \n \n\n", input);
}
system("PAUSE");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
先感谢您!!!!PS抱歉格式化我仍然习惯stackoverflow
关键短语:Double to int conversion精度错误
我认为你正在遭受浮点精度错误.
您应该能够通过以下方式解决此问题:
const double epsilon = 1e-10; // Or some suitable small number
input = floor(orgInput * 100 + epsilon) / 100;
Run Code Online (Sandbox Code Playgroud)
另一种方法是在输入时阻止这种情况发生.你不是读取一个双字符串,而是读取一个字符串,然后解析它以获得美元和美分金额(如果有的话,分数正好是小数点后面的2位数).然后你可以忽略其他一切.
一般来说,如果你正在使用截断到美分的资金,你可能最好将其保持在美分并使用整数.无论是圆形还是圆形而不是截断(对于我上面的例子,这意味着ε为0.5).