预期结果在1和0之间的除法总是给出0 [英] Division with expected result between 1 and 0 always gives 0

查看:243
本文介绍了预期结果在1和0之间的除法总是给出0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

C中整数除法的行为是什么?

当我使用应该在1和0之间的答案进行除法计算时,它总是返回0.

When I do a division calculation with an answer that's supposed to be between 1 and 0, it always returns 0.

试试这个:

float a = 1;
float b = 2;
float c = a / b; //variable divide by variable gives 0.5 as it should
float d = 1 / 2; //number divide by number gives 0
float e = 4 / 2;
NSLog(@"%f %f %f %f %f", a,b,c, d, e);

我从控制台得到这个:


2013-01-17 14:24:17.512 MyProject [1798:c07] 1.000000 2.000000 0.500000 0.000000 0.500000

2013-01-17 14:24:17.512 MyProject[1798:c07] 1.000000 2.000000 0.500000 0.000000 0.500000

我不知道发生了什么。

推荐答案

你将整数除以整数。结果将是一个整数,余数被省略:

You're dividing integer with integer. The result will be an integer, the remainder is omitted:

1 / 2 = 0     The remainder (0.5) is omitted.

只有在除法完成后,您的结果才会传递到您的浮点数d 变量。

Only after the division is done, your result is passed into your float d variable.

编辑:对,我忘了建议一个解决方案:确保至少有一个操作数是浮点数。

Right, I forgot to suggest a solution: Make sure at least one of your operands is a float.

1.0 / 2 = 0.5    

1 / 2.0 = 0.5

这篇关于预期结果在1和0之间的除法总是给出0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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