ceil()无法正常工作 [英] ceil() not working as I expected

查看:107
本文介绍了ceil()无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一个数除以另一个,然后立即将ceil()转换为结果.这些通常是变量,但为简单起见,让我们坚持使用常量.

I'm trying to divide one number by another and then immediately ceil() the result. These would normally be variables, but for simplicity let's stick with constants.

如果我尝试以下任何一种方法,当我想要得到4时我得到3.

If I try any of the following, I get 3 when I want to get 4.

double num = ceil(25/8); // 3
float num = ceil(25/8); // 3
int num = ceil(25/8); // 3

我已经在这里读过一些线程(尝试了

I've read through a few threads on here (tried the nextafter() suggestion from this thread) as well as other sites and I don't understand what's going on. I've checked and my variables are the numbers I expect them to be and I've in fact tried the above, using constants, and am still getting unexpected results.

预先感谢您的帮助.我敢肯定,这很简单,我很想念,但现在我很茫然.

Thanks in advance for the help. I'm sure it's something simple that I'm missing but I'm at a loss at this point.

推荐答案

这是因为您正在执行整数运算.在调用ceil之前,该值为3,因为25和8都是整数.首先使用整数算术计算25/8,求值为3.

This is because you are doing integer arithmetic. The value is 3 before you are calling ceil, because 25 and 8 are both integers. 25/8 is calculated first using integer arithmetic, evaluating to 3.

尝试:

double value = ceil(25.0/8);

这将确保编译器将常数25.0视为浮点数.

This will ensure the compiler treats the constant 25.0 as a floating point number.

您还可以使用显式强制转换来实现相同的结果:

You can also use an explicit cast to achieve the same result:

double value = ceil(((double)25)/8);

这篇关于ceil()无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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