Accelerated C++<4-2>

来源:互联网 发布:伯德生涯数据 编辑:程序博客网 时间:2024/04/29 04:22

//Write a program to calculate the squares of int values up to 100. The program should write two columns: The first lists the value; the second contains the square of that value. Use setw to manage the output so that the values line up in columns.



expand/collapse icon Hint

Determine the widest outputs for both columns.

expand/collapse icon Solution

The widest number that is being squared is 100, which is three digits. 100 squared is 10000, which is 5 digits, so the solution belows sets a width of 4 prior to sending the base to output and set a width of 6 prior to sending the result to output. Setting the widths one larger than the values contained will preserve at least one space to the left of each value.



#include <iomanip>
#include <iostream>
 
using std::cout;
using std::endl;
using std::setw;
 
int main()
{
   for (int i = 1; i < 101; ++i)
   {
      cout << setw(4) << i << setw(6) << (i * i) << endl;
   }
}


0 0
原创粉丝点击