浮点数相乘得到无限的值

Multiplying floats gives infinite values

本文关键字:无限 浮点数      更新时间:2023-10-16

我尝试了很多方法:

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,你可以查询。

这只是科学记数法。