以 C++ 为单位的浮点数学运算输出

floating-point math operations output in C++

本文关键字:运算 输出 浮点数 C++ 为单位      更新时间:2023-10-16

我正在尝试纠正一个简单的数学程序,但我很难获得正确格式化的输出。

下面是一个示例代码:

#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
const double PI = 3.14159265358979;
int main()
{
double a,b,c,d;
a = cos(30*PI/180);
b = sin(30*PI/180);
c = cos(90*PI/180);
d = sin(90*PI/180);
cout << a << endl;
cout << b << endl;
cout << c << endl;
cout << d << endl;
}

给出以下输出:

0.866025 0.5
1.61554e-015 1

我尝试按如下方式使用圆形,但圆形将全部舍入

cout << round(a) << endl;
cout << round(b) << endl;
cout << round(c) << endl;
cout << round(d) << endl;  

它给出了以下输出:


1 0 0
1

最后我尝试修复,但它是固定的

cout << fixed << a << endl;
cout << fixed << b << endl;
cout << fixed << c << endl;
cout << fixed << d << endl;

输出

0.866025
0.500000 0.000000 1.000000

我试图得到的是输出输出,如下所示:

0.866025
0.5
0 1

我知道浮点很难处理,因为有限的存储空间表示无限。

我浏览了很多关于浮点数的阅读,但没有找到如何仅使用标准C++库获得所需的结果。

而且由于角度 30 和 90 只是一个样本,我不能为每个变量使用不同的输出技术。

我宁愿尽可能长时间地坚持cout而不是printf。

我提前感谢您的帮助。

我认为有问题的输出是使用科学记数法c的输出。如果是这样,则需要单独处理这些值:灵活的格式(既不设置std::ios_base::fixed也不设置std::ios_base::scientific,格式等效于使用printf()%g格式)将以尽可能表示具有设置精度的值的方式打印值。当需要位数来合理表示值时,此方法将使用科学记数法。

处理这种情况的一种方法是显式检测"错误"值,例如,低于某个阈值的值。如果要避免单独检查每个输出,则可以imbue()具有自定义std::num_put<...>分面的自定义std::locale对象,例如:

#include <iostream>
#include <locale>
#include <iomanip>
#include <cmath>
const double PI = 3.14159265358979;
struct num_put: std::num_put<char> {
iter_type do_put(iter_type to, std::ios_base& fmt, char_type fill, double v) const {
if (v < 1e-4) {
*to = '0';
++to;
return to;
}
return std::num_put<char>::do_put(to, fmt, fill, v);
}
};
int main()
{
std::cout.imbue(std::locale(std::locale(), new num_put));
double a,b,c,d;
a = std::cos(30*PI/180);
b = std::sin(30*PI/180);
c = std::cos(90*PI/180);
d = std::sin(90*PI/180);
std::cout << a << 'n';
std::cout << b << 'n';
std::cout << c << 'n';
std::cout << d << 'n';
}

这个快速演示还修复了一些不相关的问题:

  • 不要使用std:endl:如果您的意思是显式刷新流,请使用std::flush
  • using指令不好