Accelerated C++<4-2>

本文介绍了一个简单的程序设计方法,用于计算并打印从1到100的所有整数及其平方值。通过使用setw来设置输出宽度,确保数值整齐地排列成两列:左侧为整数,右侧为对应的平方值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//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;
   }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值