PTA|基础编程题目集|7-14

解题

对整数区间进行循环输出即可,是否换行使用计数器对5取模即可。结果直接使用等差数列求和得出,无需循环累加。

关键点

循环遍历输出、计数器判断是否换行,占据格式

参考代码

#include <iostream>
#include <iomanip>			                //格式控制
using namespace std;
int main()
{
	int starter,stop;
	cin>>starter>>stop;
	int sum=(starter+stop)*(stop-starter+1)/2;      //等差求和
	int total=0;
	for(int i=starter;i<=stop;i++)			//循环输出
	{
		cout<<setw(5)<<i;
		total+=1;
		if (total%5==0)
		{
			cout<<endl;		       //每5个换行一次
		}
	}

	// 最后一行的控制——刚好是5的整数倍时不需要再次换行
	if(total%5==0)
	{
		cout<<"Sum = "<<sum<<endl;
	}
	else{
		cout<<endl<<"Sum = "<<sum<<endl;
	}

	return 0;
}
原文地址:https://www.cnblogs.com/reaptem/p/14003403.html