math.h ceil不能按预期工作 [英] math.h ceil not working as expected in C

查看:139
本文介绍了math.h ceil不能按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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?

任何人都可以解释为什么这两种情况都发生了?也是我编译使用CC版本4.1.2在RedHat。

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.

您应该阅读Goldberg的报告,名为每个计算机科学家应该知道的浮点算术

You should read Goldberg's report called What Every Computer Scientist Should Know About Floating-Point Arithmetic.

这篇关于math.h ceil不能按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆