我正在学习 setw 和 set precision 函数,所以这是我到目前为止一直在尝试的,我有几个问题。
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
float y = 1.25;
cout << fixed << setw(10) << setprecision(2) << y << endl;
cout << "\n\n\nx\n";
float x = 213565544.4826;
cout << fixed << setw(13) << setprecision(3) << x << endl;
cout << fixed << setw(14) << setprecision(3) << x << endl;
cout << fixed << setw(15) << setprecision(3) << x << endl;
cout << fixed << setprecision(3) << x;
cout << "\n\n\nz\n";
float z = 213565544.4826;
cout << setw(11) << setprecision(1) << x << endl;
cout << fixed << setw(12) << setprecision(1) << x << endl;
cout << fixed << setw(11) << setprecision(1) << x << endl;
cout << setw(12) << setprecision(1) << x << endl;
cout << "\n\n\nm\n";
float m = -344.275;
cout << fixed << setprecision(1) << x << endl;
cout << fixed << setw(8) << setprecision(1) << x << endl;
cout << fixed << setw(7) << setprecision(1) << x << endl;
cout << fixed << setw(6) << setprecision(1) << x << endl;
return 0;
}
输入是:
1.25
x
213565552.000
213565552.000
213565552.000
213565552.000
z
213565552.0
213565552.0
213565552.0
213565552.0
m
213565552.0
213565552.0
213565552.0
213565552.0
所以,现在我的问题是:
1)为什么我们首先使用“固定”?
如果我们看这个例子:
cout << setw(11) << setprecision(1) << x << endl;
cout << fixed << setw(11) << setprecision(1) << x << endl;
它们输出相同的值,那么fixed到底改变了什么?
2) setw 如何处理负数?
在 m 的最后一个例子中。所有示例的结果都是相同的,setw 中的 - 符号发生了什么变化?
213565552.0
213565552.0
213565552.0
213565552.0
这些数字从何而来?m的值与输出的值完全不同。
3) 是否.数字算作 1 位吗?
例如,我们有数字 1.23 和 setw(10)
前面有 6 个空格,后面有 1.23(因为点算作 1)。真的吗?
4)为什么set precision与setw一起使用?不使用的话为什么会出现0000呢?它是否出现了浮点数可以处理的尽可能多的 0?
5) 为什么x的值是
213565552.000
213565552.000
213565552.000
213565552.000
如果 x = 213565544.4826。
数字 44.4826 在哪里丢失了?