【问题标题】:When printing a float, how can you print decimal places more precisely?打印浮点数时,如何更精确地打印小数位?
【发布时间】:2021-05-15 20:27:27
【问题描述】:

我对编码很陌生,但我遇到了一个非常基本的问题。我已经编写了一个程序来执行一个基本方程和printf 结果:

#include <stdio.h>

int main (void)
{
    float f = (380 / 3);
    
    printf("%f\n", f);
}

但是,我得到的结果是126.000000。如何让我的程序更精确地打印出小数位?

【问题讨论】:

标签: c floating-point printf


【解决方案1】:

如何让我的程序更精确地打印出小数位?

第 1 步,使用 浮点 FP 数学,而不是整数数学。

// float f = (380 / 3);      // int math
// float f = 380.0f / 3.0f;  // float math
double f = 380.0 / 3.0;      // double math

第 2 步:指定一个大于默认值 6 的 精度。

int prec = 7;
printf("%.*f\n", pre, f);

...或者更好,使用指数表示法

printf("%.*e\n", FLT_DECIMAL_DIG, f); 

....甚至是十六进制。

printf("%a\n", f); 

#include <float.h>
#include <stdio.h>

int main(void) {
  double f = 380.0 / 3.0;
  int prec = 7;
  printf("%.*f\n", prec, f);
  printf("%.*e\n", DBL_DECIMAL_DIG, f);
  printf("%a\n", f);
}

输出

126.6666667
1.26666666666666671e+02
0x1.faaaaaaaaaaabp+6

【讨论】:

    猜你喜欢
    • 2011-03-14
    • 1970-01-01
    • 2012-07-14
    • 2020-08-04
    • 2012-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多