Division with expected result between 1 and 0 always gives 0 [duplicate]

≯℡__Kan透↙ 提交于 2019-12-04 07:00:00

问题


Possible Duplicate:
What is the behavior of integer division in C?

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

Try this:

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);

I get this from the console:

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

I have no idea what is going on.


回答1:


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.

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

EDIT: 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


来源:https://stackoverflow.com/questions/14370857/division-with-expected-result-between-1-and-0-always-gives-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!