浮点数乘法会返回意外结果

Lio*_*ior 2 c# floating-point double

int countBouncy=5;
int count=999899;

double percent = (double)(countBouncy / count) * 100.0;
Run Code Online (Sandbox Code Playgroud)

这句话的结果出乎意料,我得零.

为什么它不起作用?

Oli*_*bes 6

你正在进行整数除法(countBouncy / count).将您的代码更改为

double percent = ((double)countBouncy / count) * 100.0;
Run Code Online (Sandbox Code Playgroud)

这样,将countBouncydouble显式count转换为doublec#编译器隐式转换为使其与(now double)兼容countBouncy.

否则(countBouncy / count)计算为(5 / 999899) --> 0因为两者都是整数.


整数除法如何工作?我们来举个例子:

7 / 2 = 3
Run Code Online (Sandbox Code Playgroud)

整数除法会丢弃实数除法产生的小数部分.结果被截断为零.您可以使用模运算符来获得该除法的剩余部分

7 % 2 = 1
Run Code Online (Sandbox Code Playgroud)

并执行这样的反向计算

2 * (7 / 2) + 7 % 2 = 7
Run Code Online (Sandbox Code Playgroud)

您可以在Visual Studio的即时窗口中输入它来测试它:

?2*(7/2)+ 7%2 <enter>
7