【问题标题】:Division with expected result between 1 and 0 always gives 0 [duplicate]预期结果在 1 和 0 之间的除法总是给出 0 [重复]
【发布时间】:2012-12-31 12:09:39
【问题描述】:

可能重复:
What is the behavior of integer division in C?

当我用一个应该在 1 和 0 之间的答案进行除法计算时,它总是返回 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

我不知道发生了什么。

【问题讨论】:

  • thisthisthisthisthis
  • 你可以做 1.f/2, 1.0/2, 1/2.0000f, 1/(float)2... 基本上除了 2 个整数之外的任何东西
  • 嘿,等一下……你怎么把0.500000 换成了e4 / 2?应该是2.000000
  • @Pang:他的裤子着火了。

标签: objective-c math integer division


【解决方案1】:

你用整数除以整数。结果为整数,余数省略:

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

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

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

1.0 / 2 = 0.5    

1 / 2.0 = 0.5

【讨论】:

  • 要修复它,至少使用一个显式浮点数作为操作数:1.0 / 2;1 / 2.0;
猜你喜欢
  • 2015-11-20
  • 2022-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-17
  • 1970-01-01
  • 2021-12-28
  • 2013-06-27
相关资源
最近更新 更多