Objective-C中计算浮点数的奇怪值

时间:2013-03-18 08:30:58

标签: ios objective-c c

我的应用程序是这样计算的。

float containTaxValue = 840;
float taxRate = 5;
float divisionedNum = (100 + taxRate)/100;
float removedTaxValue = containTaxValue/divisionedNum;
float taxValue = containTaxValue - removedTaxValue;

最后答案是

NSLog(@"%f",removedTaxValue); => 800.000061
NSLog(@"%f",containTaxValue); => 840.000000
NSLog(@"%f",taxValue); => 39.999939

我想在此代码中获得“taxValue == 40.000000”。

我无法理解什么是问题。请告诉我任何建议。

4 个答案:

答案 0 :(得分:2)

IEEE 754标准是一种以机器易于操作的方式存储浮点数的方法。这种方法由INtel和处理器的mot使用。

IEEE 754规定以二进制格式存储数字以降低存储要求,并允许所有微处理器上可用的内置二进制算术指令以相对快速的方式处理数据。但是,一些简单的非重复十进制数字转换为重复的二进制数,无法以完美的精度存储。

1/10可以用小数形式表示.1

但是以二进制形式它变成: .0001100011000111000111(依此类推)

And Hence the rounding-off error occurs.

您必须将其转换为int才能将其四舍五入。

1.05的二进制转换也在继续 00111111 10000110 01100110 01100110 ....

答案 1 :(得分:1)

float无法准确表示许多值,例如1.05。舍入错误发生并结转到最终结果。

答案 2 :(得分:0)

如果您不确定点后数字的长度,可以使用%.6f而不是简单的%f来打印精确的6位数后点,以对可以使用的值进行舍入{{1函数,它将对值进行四舍五入。

仅限ceil(double)

%f

输出,40.000000

float taxValue = 39.999999; // you've 6 digits after dot NSLog(@"%f",ceil(taxValue));

%.6f

输出,40.000000

答案 3 :(得分:0)

要向上舍入浮点值,您可以使用以下代码

float A,B; // this variables have to be floats!
int roundDown = floor(A/B); // rounded down
int roundUp = ceil(A/B); // rounded Up
int rounded = lroundf(theFloat); //rounded

结果int值再次转换为float

希望这有助于!!!