PTA finds the sum of integer segments

Find the integer segment sum (10 points)
Given two integers A and B, output all integers from A to B and the sum of these numbers.

Input format:
Input two integers A and B in one line, where −100≤A≤B≤100, separated by spaces.

Output format:
first output all the integers from A to B in order, each 5 digits occupy a line, each digit occupies 5 characters width, aligned to the right. Finally, output the sum X of all numbers in the format of Sum = X in one line.

Input sample:

-3 8

Sample output:

   -3   -2   -1    0    1
    2    3    4    5    6
    7    8
Sum = 30

Code

#include<iostream>
#include<string.h> 
using namespace std;

int main()
{
    
    
	int m,n;
	cin>>m>>n;
	int i,sum=0,j=0;
	for(i=m;i<=n;i++)
	{
    
    
		printf("%5d",i);
		j++;
		if(j%5==0&&i!=n) cout<<endl; //开始时写的是if(j%5==0) 
		//没有考虑到如果这样的话只有五个数的时候也会换行,本来是不需要换行的 
		sum+=i;
	}
	
	cout<<endl<<"Sum = "<<sum;
	return 0;
} 


Why did you post this? It was originally a very simple question. I missed a bit. When I submitted it, there was a sample that was wrong. Later I thought about it and found the error. See the code for details!
Big guys are welcome to advise. If you don’t understand, you can comment or add Q2651877067. If you see it, you will reply as soon as possible! ! !

Guess you like

Origin blog.csdn.net/mmmjtt/article/details/113953044