浮点数相乘得到无限的值
Multiplying floats gives infinite values
我尝试了很多方法:
float a = 1234.34;
float b = 1234.52;
float r = a * b;
cout << r << endl;
float c = 1234.34 * 1234.52;
cout << c << endl;
cout << 1234.34 * 1234.52 << endl;
cout << (float)(1234.34 * 1234.52) << endl;
所有这些似乎都给出了无限的值。
1.52382e+006
1.52382e+006
1.52382e+006
1.52382e+006
我在这里做错了什么?
结果中的数字远不接近无穷大。
结果只是c++用科学记数法显示值。
请查看如何避免使用科学记数法处理大数
这些值不是无限的,它们只是科学记数法。
1.52382e+006
求值为1.52382 * (10)^6
。
您可能希望使用doubles
,并为ostream
设置精度:
#include <limits> // std::numeric_limits
#include <iostream> // std::cout
int main() {
double f = 3.141592;
std::cout.precision(std::numeric_limits<double>::digits10);
std::cout << std::fixed;
std::cout << f;
return 0;
}
答案正确。1.52382e+006等于1.52382 * 106
如果你不想要E格式的输出,使用std::fixed
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
float a = 1234.34;
float b = 1234.52;
float r = a * b;
cout << std::fixed << r << endl;
float c = 1234.34 * 1234.52;
cout << std::fixed << c << endl;
cout << std::fixed << 1234.34 * 1234.52 << endl;
cout << std::fixed << (float)(1234.34 * 1234.52) << endl;
return 0;
}
这段代码输出如下
1523817.375000
1523817.375000
1523817.416800
1523817.375000
你得到的是你的结果的科学记数法,1523817.4168,在科学记数法中是1.52382E+6,其中E代表"10^",意思是1.52382 * 10^ 6,你可以查询。
这只是科学记数法。
相关文章:
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 如何修复此错误:未定义对"距离(浮点数,浮点数,浮点数,浮点数,浮点数)"的引用
- C++浮点数据类型和字符串数据类型无法子到模板函数中
- 使用提升将数据从 PyObject 复制到浮点数 *
- 使用浮点数和双精度数的非常小数字的数学
- 使用英特尔内联函数将打包的 8 位整数乘以浮点数向量
- 如何在 c++ 中将小数点后两位数的浮点数分配给另一个浮点数
- 返回浮点数的小数位数
- txt 文件中浮点数的最大和最小值
- 为什么 std::cout 打印浮点数、双精度和长双精度到相同的小数精度?
- 将浮点数转换为无符号字符数组并打印出来
- 如何将时间字符串 (M:SS) 转换为浮点数
- 如何将浮点数(*)[6]转换为浮点**类型?
- C++将浮点数乘以分数
- 如何将浮点数转换为uint8_t?
- 将字符串转换为浮点数或整数,而无需使用内置函数(如 atoi 或 atof)
- 如何在C++(Arduino)中将浮点数组转换为字节数组
- 浮点数的无限是否满足这些方程
- 浮点数相乘得到无限的值
- 在visual basic、java或c++中是否有可能拥有无限精度的浮点数据类型?