使用 float 和 double 对非常小的数字进行数学运算
math with very small numbers using float and double
我写这段代码只是为了看看使用浮点数和双精度值时精度值的差异。
基本上我正在尝试计算减少的普朗克常数的值。
约化普朗克 const = Plancks const/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
我减少了常量中的有效数字,但没有任何区别。
谁能告诉我我做错了什么?
printf("float is %ld \ndouble is %ld", a, b);
%d
是整数的格式说明符,而不是浮点数。请改用 %f
,它将适用于 double
,并且由于自动参数提升,%f
也适用于 float
。
大多数编译器都会对此类错误发出警告。确保您在编译器中启用了警告。对于 GCC,使用 -Wall -Wextra
.
%ld
应该得到一个 long int
作为参数,而不是 double。尝试 %f
、%e
、%g
,您可以选择使用其他修饰符,或 printf
.
支持的其他格式
此外,您应该考虑启用编译器警告,例如 -W -Wall
with 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
.
等可变参数函数一起使用时会被提升
在您的示例中,计算基本相同:H / (2 * Pi)
计算均以浮点数形式执行,之后结果转换为 double
:在一种情况下,因为 b
是 double
,在另一种情况下,由于 printf
.
的促销规则
我写这段代码只是为了看看使用浮点数和双精度值时精度值的差异。 基本上我正在尝试计算减少的普朗克常数的值。 约化普朗克 const = Plancks const/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
我减少了常量中的有效数字,但没有任何区别。 谁能告诉我我做错了什么?
printf("float is %ld \ndouble is %ld", a, b);
%d
是整数的格式说明符,而不是浮点数。请改用 %f
,它将适用于 double
,并且由于自动参数提升,%f
也适用于 float
。
大多数编译器都会对此类错误发出警告。确保您在编译器中启用了警告。对于 GCC,使用 -Wall -Wextra
.
%ld
应该得到一个 long int
作为参数,而不是 double。尝试 %f
、%e
、%g
,您可以选择使用其他修饰符,或 printf
.
此外,您应该考虑启用编译器警告,例如 -W -Wall
with 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
.
在您的示例中,计算基本相同:H / (2 * Pi)
计算均以浮点数形式执行,之后结果转换为 double
:在一种情况下,因为 b
是 double
,在另一种情况下,由于 printf
.