问题:数学老师请你帮忙,在屏幕上输出10+870的竖式计算,如下图所示:
程序如下:
#include <iostream>
using namespace std;
int main()
{
int a,b,s;
a = 18;
b = 780;
s = a + b;
cout << " " << a << endl; //8个空格
cout << " + " << b << endl; //+号前后分别3个空格
cout << "-----------" << endl; // 11 个 -
cout << " " << s << endl; //7个空格
return 0;
}
运行结果如下:
如果我们让a=18000;
结果如下:
格式出现了混乱,我们要想个新办法:
#include <iostream>
#include <iomanip> //为了使用setw操作符来设置域宽
using namespace std;
int main()
{
int a,b,s;
a = 18000;
b = 780;
s = a + b;
cout << setw(10) << a << endl;
cout << setw(4) << '+' << setw(6) << b << endl;
cout << "-----------" << endl;
cout << setw(10) << s << endl;
return 0;
}