resultPercentage = (x/(x+y))*1000;
不作为(x/(x+y))
可能0
or 1
乘法之前*1000
发生。反而:
对于四舍五入的无符号整数计算x/(x+y)
, let a = x
and b = x+y
然后找到a/b
use:
result = (a + b/2)/b;
对于四舍五入的无符号整数百分 % http://en.wikipedia.org/wiki/Percent的计算a/b
use
result = (100*a + b/2)/b;
对于四舍五入的无符号整数permil ‰ http://en.wikipedia.org/wiki/Permil的计算a/b
use
result = (1000*a + b/2)/b;
对于四舍五入的无符号整数无数‱ http://en.wikipedia.org/wiki/Basis_point的计算a/b
use
result = (10000*a + b/2)/b;
担心吃掉整数范围:使用更广泛的整数数学(unsigned long long
)用于乘法,也许x+y
.
result = (100ULL*a + b/2)/b;
For signed a, b
,它更复杂,因为b/2
需要匹配的符号a/b
.
if (b > 0) {
if (a >= 0) {
result = (a + b/2)/b;
} else {
result = (a - b/2)/b;
}
} else {
if (a >= 0) {
result = (a - b/2)/b;
} else {
result = (a + b/2)/b;
}
}
可以对单行进行编码:
result = (a + (((a < 0)==(b < 0)) ? b/2 : b/-2))/b;
b/-2
比-b/2
预防 UBb == INT_MIN
。或者使用-(b/2)
.
当然,更换
// printf(resultPercentage);
printf("%d\n", resultPercentage);
// or for unsigned
printf("%u\n", resultPercentage);