以 C++ 为单位的浮点数学运算输出
floating-point math operations output in C++
我正在尝试纠正一个简单的数学程序,但我很难获得正确格式化的输出。
下面是一个示例代码:
#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
指令不好
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 使用C++中的模板和运算符重载执行矩阵运算
- 请解释"函数1(p1,p2,p3);"的输出
- C++:将控制台输出存储在宏中更好吗
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 为什么我的代码在输出中增加了93天
- 如何从void函数输出字符串
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- AES加密到解密未正确输出
- 如何将c++程序的一些输出传递给shell,以便在shell中使用
- 使用C++程序合并排序没有得到正确的输出
- GCC本机矩阵运算库
- 以 C++ 为单位的浮点数学运算输出
- 有没有一种方法可以将阈值运算输出存储在Eigen(C++)中
- 为什么 bool 显示正确的位顺序,而直接输出移位运算结果却不显示?
- 逻辑AND运算对流输出的作用
- 对一元运算如何产生此输出感到困惑
- 从输入文件到输出文件的运算