首页 > 解决方案 > 使用浮点数和双精度数非常小的数学

问题描述

我编写此代码只是为了查看使用浮点数和双精度值时精度值的差异。基本上我正在尝试计算减少的普朗克常数的值。约简普朗克常数 = 普朗克常数/2π。

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

const float H = 6.62607015e-34;
const float Pi = 3.1415926;
int main()
{
    float a = H / (2 * Pi);
    double b = H / (2 * Pi);
    printf("float is %ld \ndouble is %ld", a, b);
    return 0;
}

但是输出根本没有意义。我不知道我在这里做错了什么。

float is 536870912
double is 954303911

我什至尝试将常量的数据类型更改为 double,但效果并不好。

float is 0
double is 954303911

我减少了常数中的有效数字,但没有任何区别。谁能告诉我我在这里做错了什么?

标签: c++cdoublephysics

解决方案


%ld应该得到一个long int作为参数,而不是双倍。尝试%f, %e, %g, 使用您选择的附加修饰符,或 . 支持的其他格式 printf

此外,您应该考虑启用编译器警告,例如-W -Wall使用 gcc:

: In function 'main':
:10:5: warning: format '%ld' expects argument of type 'long int', but argument 2 has type 'double' [-Wformat=]
     printf("float is %ld \ndouble is %ld", a, b);
     ^
:10:5: warning: format '%ld' expects argument of type 'long int', but argument 3 has type 'double' [-Wformat=]

参数具有类型double,因为float在与 varargs 函数(如printf.

在您的示例中,计算基本相同:两次H / (2 * Pi)计算都以浮点数形式执行,然后结果转换为double: 在一种情况下是因为bisdouble而在另一种情况下是由于printf.


推荐阅读