C++ 使用浮点数和双精度的非常小的数字的数学

C++ 使用浮点数和双精度的非常小的数字的数学,c++,c,double,physics,C++,C,Double,Physics,我写这段代码只是为了在使用float和double时看到精度值的差异。 基本上我是在计算约化普朗克常数的值。 约化普朗克常数=普朗克常数/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);

我写这段代码只是为了在使用float和double时看到精度值的差异。 基本上我是在计算约化普朗克常数的值。 约化普朗克常数=普朗克常数/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;
}
我甚至尝试将常量的数据类型改为double,但效果并不好

float is 0
double is 954303911
我减少了常量中的有效数字,但没有任何区别。 谁能告诉我我做错了什么

printf("float is %ld \ndouble is %ld", a, b);
%d是整数的格式说明符,而不是浮点数。改用%f,它将适用于double,并且由于参数自动升级,%f也适用于float

大多数编译器都会对这种错误发出警告。确保在编译器中启用了警告。对于GCC,使用-Wall-Wextra。

%ld应该获得一个长int作为参数,而不是双精度。请尝试%f、%e、%g,并选择其他修饰符,或使用支持的其他格式

此外,您应该考虑启用编译器警告,例如-WC-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在与诸如printf之类的varargs函数一起使用时会被提升


在您的示例中,计算基本相同:两个H/2*Pi计算都以浮点形式执行,然后将结果转换为double:一种情况是因为b是double,另一种情况是因为printf的升级规则。

%ld用于整数,而不是float或double,使用%E表示科学符号。启用编译器warnings@GauravDhiman谢谢,我不知道%E。但是每当我包含math.h时,%ld用于float和double。@shryapatil:%ld不用于float或double,无论是否包含math.h。如果你认为是这样的话,那么你就被某些巧合所愚弄了,或者你愚弄了自己。
: 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=]