c++ - 使用浮点数和双精度数非常小的数学
问题描述
我编写此代码只是为了查看使用浮点数和双精度值时精度值的差异。基本上我正在尝试计算减少的普朗克常数的值。约简普朗克常数 = 普朗克常数/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
我减少了常数中的有效数字,但没有任何区别。谁能告诉我我在这里做错了什么?
解决方案
%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
: 在一种情况下是因为b
isdouble
而在另一种情况下是由于printf
.
推荐阅读
- python - TypeError: create_int(): 不兼容的函数参数
- python - Python迭代器下一个方法
- javascript - 为什么我的 mongodb 图表嵌入 sdk 不起作用?
- php - 在路由 Laravel 中向控制器发送参数
- android-sqlite - 在sqlite android中设置布尔值
- java - Gradle 在 debugMode 中抛出异常。线程“主”java.net.UnknownHostException 中的异常:
- amazon-web-services - http.max_content_length 的 Amazon OpenSearch 等效项是多少,我可以增加它吗?
- arrays - 具有可变整数数组的 C 程序的未知行为
- wpf - Wpf 文本框无法输入数字和字母
- mysql - 测试连接时出现PopSQL错误:Can't connect to local MySQL server through socket '/run/mysqld/mysqld.sock' (2)