PAT基础编程题目-7-14 求整数段和
PAT基础编程题目-7-14 求整数段和
题目详情
解答
C语言版
#include<stdio.h>
int main() {
int a, b, sum = 0, count=1;
scanf("%d %d", &a, &b);
for (int i = a; i <= b; i++, count++)
{
printf("%5d", i);
if (count % 5 == 0)
printf("\n");
sum = sum + i;
}
if((count-1)%5==0) // 避免多换行一次
printf("Sum = %d", sum);
else
printf("\nSum = %d", sum);
return 0;
}
C++版
#include<iostream>
#include<iomanip>
using namespace std;
int main() {
int a, b, sum = 0, count = 1;
cin >> a >> b;
for (int i = a; i <= b; i++, count++)
{
cout << setw(5) << i; //设置宽度setw
if (count % 5 == 0)
cout << endl;
sum = sum + i;
}
if ((count - 1) % 5 == 0) // 避免多换行一次
cout << "Sum = " << sum;
else
cout << endl << "Sum = " << sum;
return 0;
}
Java版
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
int a = 0, b = 0, sum = 0, count = 1;
Scanner scanner = new Scanner(System.in);
if (scanner.hasNext()) {
a = scanner.nextInt();
b = scanner.nextInt();
}
scanner.close();
for (int i = a; i <= b; i++, count++)
{
/** * String.format(): * 可对整数进行格式化:%[index$][标识][最小宽度]转换方式 * %[index$]:以%index$开头,index从1开始取值,表示将第index个参数拿进来进行格式化 * [标识]:' ' 正值前加空格,负值前加负号 * [最小宽度]:最终该整数转化的字符串最少包含多少位数字 * 转换方式:d-十进制 o-八进制 x或X-十六进制 */
System.out.print(String.format("%1$ 5d", i));
if (count % 5 == 0)
System.out.println();
sum = sum + i;
}
if ((count - 1) % 5 == 0) // 避免多换行一次
System.out.print("Sum = "+sum);
else
System.out.print("\nSum = "+sum);;
}
}
创作不易,喜欢的话加个关注点个赞,谢谢谢谢谢谢!