问题描述
为什么CEIL()向上舍甚至没有小数部分浮动?结果
当我尝试这样做:
How come ceil() rounds up an even floating with no fractional parts?
When I try to do this:
double x = 2.22;
x *= 100; //which becomes 222.00...
printf("%lf", ceil(x)); //prints 223.00... (?)
但是,当我的2.22的值更改为2.21
But when I change the value of 2.22 to 2.21
x *= 100; //which becomes 221.00...
printf("%lf", ceil(x)); //prints 221.00... as expected
我试图做这样使用MODF(另一种方法),并遇到了另一个奇怪的事情:
I tried to do it another way like this using modf() and encountered another strange thing:
double x = 2.22 * 100;
double num, fraction;
fraction = modf(x, &num);
if(fraction > 0)
num += 1; //goes inside here even when fraction is 0.00...
那么,什么情况是0.000 ...大于0?结果
任何人都可以解释为什么这两种情况都发生了什么?另外我在redhat使用CC版本4.1.2编译。
So what happens is 0.000... is greater than 0?
Can anyone explain why both of these situations are happening? Also I'm compiling using cc version 4.1.2 in RedHat.
推荐答案
这是正常的,因为数字是使用二进制存储。虽然你的号码可在有限的数字使用的数字小数点写成,这并不持有的二进制文件。
This is normal as numbers are stored using binary. While your numbers can be written in finite numbers of digits using decimal, this does not hold for binary.
您应该阅读戈德堡报告名为。
You should read Goldberg's report called What Every Computer Scientist Should Know About Floating-Point Arithmetic.
这篇关于文件math.h CEIL未按预期用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!