gpt4 book ai didi

C如何计算没有浮点精度的百分比(perthousands)

转载 作者:太空狗 更新时间:2023-10-29 15:19:53 29 4
gpt4 key购买 nike

如何将 2 个 int 值的百分比计算为表示百分比(以千为单位更准确)的 int 值?

背景/目的:使用没有 FPU 的处理器,浮点计算时间要长 100 倍。

int x = 25;
int y = 75;
int resultPercentage; // desire is 250 which would mean 25.0 percent

resultPercentage = (x/(x+y))*1000; // used 1000 instead of 100 for accuracy
printf("Result= ");
printf(resultPercentage);

输出:

结果= 0

当我真正需要的是 250 时。我不能使用任何浮点计算。

正常fpu计算的例子:

int x = 25;
int y = 75;
int resultPercentage; // desire is 250 which would mean 25.0 percent

resultPercentage = (int)( ( ((double)x)/(double(x+y)) ) *1000); //Uses FPU slow

printf("Result= ");
printf(resultPercentage);

输出:

结果= 250

但输出是以使用浮点计算为代价的。

最佳答案

resultPercentage = (x/(x+y))*1000; 不起作用,因为 (x/(x+y)) 可能是 0 1 在乘法 *1000 发生之前。相反:

对于 x/(x+y) 的四舍五入无符号整数计算,让 a = xb = x+y 然后查找 a/b 使用:

result = (a + b/2)/b;

对于四舍五入的无符号整数 percent % a/b的计算使用

result = (100*a + b/2)/b;

对于四舍五入的无符号整数 permil ‰ a/b的计算使用

result = (1000*a + b/2)/b;

对于四舍五入的无符号整数 permyriad ‱ a/b的计算使用

result = (10000*a + b/2)/b;

@H2CO3 wells 指出了对占用整数范围的担忧,因此乘法需要使用更宽的整数(longlong long),也许 x+y.

result = (100L*a + b/2)/b;

当然是替换

// printf(resultPercentage);
printf("%d\n", resultPercentage);

关于C如何计算没有浮点精度的百分比(perthousands),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20788793/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com