【问题标题】:How to format float in C without most significant digits?如何在没有最高有效数字的情况下格式化 C 中的浮点数?
【发布时间】:2020-02-05 05:39:08
【问题描述】:

我想输出数据是这样的

input : 1999.99
output: 999.99 

我想删掉更重要的数字。

我用过这样的C格式

%.2f  ==> 10.44, 23.23, 5.67

现在我需要在小数点前截断。

有什么办法吗?

【问题讨论】:

  • I wanna output data look like this I wanna cut out the excess data. - 所以你想让你的数据看起来像这样吗?哪些数据是“多余数据”? i need to cut before decimal point. - 所以你需要你的数据“看起来像这样”,或者你需要在小数点前删减? “小数点前”“删减”数字是什么意思?
  • 那么你需要取模1000.0的值吗?从<math.h> 中寻找modf()(或者是fmod()?)。
  • @KamilCuk 我向您展示了多余的数据是 1000.00。例如,如果输入数据为 18734.34566,则为 734.34
  • 输出 = fmod(输入, 1000.0);
  • "没有最高有效数字?"标题不清楚。像 1.25 这样没有最高有效数字的数字将是 0.25,但您似乎想要 1.25。对于像 999.9950001 这样的输入,你想要 000.00 还是什么?有了-1999.99,你要-999.99吗?

标签: c format numbers double


【解决方案1】:

可以使用fmod() 函数获得所要求的截断额外高位数字:

#include <math.h>
#include <stdio.h>

void format_3_2(double input) {
    printf("%.2f", fmod(input, 1000.0));
}

输入:1999.99
输出:999.99

但请注意,您还应该在应用fmod() 函数之前对输入值进行四舍五入以避免这种情况:printf("%.2f", fmod(1999.999, 1000.0)); -> 1000.00。为此使用round 函数:

#include <math.h>
#include <stdio.h>

void format_3_2(double input) {
    printf("%.2f", fmod(round(input * 100.0) / 100.0, 1000.0));
}

输入:1999.999
输出:0.00

【讨论】:

  • 尝试在 fmod 之前舍入是不正确的,因为当 input * 100,.0 中的产品必须舍入为浮点格式时,它可能会增加错误。由于这个原因,使用round(input * 100.0) / 100.0 进行舍入通常是不正确的。如果 OP 希望在格式化为小数点后两位数时包含数字“000.00”的结果因此显示(或为“0.00”或类似的),并且希望不包含这些数字的数字不因此显示,则必须使用更复杂的舍入方法……
  • 由于执行这种舍入的数值技术很复杂,对于许多程序员来说,最简单的方法就是使用sprintf 格式化数字,然后对字符串执行任何字符操作以实现他们想要的任何效果.
  • #include &lt;math.h&gt; void format_3_2(double input) { printf("%.2f", fmod(round(input * 100.0)) / 100.0, 1000.0)); } --> "error: too little arguments to function 'fmod'", "error: expected ';' ')' 标记之前","错误:')' 标记之前的预期语句"。需要审核。
猜你喜欢
  • 2013-06-17
  • 2016-09-11
  • 1970-01-01
  • 1970-01-01
  • 2011-12-20
  • 1970-01-01
  • 2010-10-08
  • 2014-01-22
相关资源
最近更新 更多