如何将结果四舍五入到第三位后的第三位。
float result = cos(number);
请注意,我要将结果保存到第三位,不四舍五入。不,我不想用 .3f 打印它,我需要将它保存为新值;
例子:
0.00367 -> 0.003
注意3 之后不需要额外的零。
此外,我需要能够获得第 3 位数字。例如,如果它是 0.0037212,我想获取 3 并将其用作某些计算中的 int。
最佳答案
0.00367 -> 0.003
float
通常可以准确表示大约 232 个不同的值。 0.00367
和 0.003
不在该集合中。
最接近0.00367
的float
是0.0036700000055134296417236328125
最接近 0.003__
的 float
是 0.0030000000260770320892333984375
I want to save the result up to the third digit
这个目标需要妥协。将结果保存为接近 0.001 倍数的 float
。
按 1000.0 缩放、截断和除以 1000.0 将适用于大多数值。
float y1 = truncf(x * 1000.0f) / 1000.0f;
上面给出了一个稍微错误的答案,其中一些值接近 x.xxx000...
和 x.xxx999...
。使用更高的精度可以解决这个问题。
float y2 = (float) (trunc(x * 1000.0) / 1000.0);
I want to get the 3 and use it as an int in some calculation.
跳过非缩放部分,使用fmod()
只保留1位。
int digit = (int) fmod((trunc(x * 1000.0), 10);
digit = abs(digit);
最后,我怀疑这种方法不会完全满足 OP 未说明的“在某些计算中将其用作 int
”。 FP 数学有很多副标题,尤其是在尝试使用 binary FP 时,就像大多数 double
一样,以某种decimal 的方式。
也许以下将满足 OP 的目标,即使它做了一些舍入。:
int third_digit = (int) lround(cos(number)*1000.0) % 10;
third_digit = abs(third_digit);
关于c - 将 float 结果保存到第三位,C 中不四舍五入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45063993/