P137 5.求Sn=a+aa+aaa+...+aa...a(n个a)之值,其中a是一个数字
n表示a的位数,n由键盘输入。例如:
2+22+222+2222+22222(此时n=5)
一:C语言实现
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
//P137 5.求Sn=a+aa+aaa+...+aa...a(n个a)之值,其中a是一个数字
//n表示a的位数,n由键盘输入。例如:
//2+22+222+2222+22222(此时n=5)
int main() {
int a=0, n=0, i = 1, Sn = 0, Tn = 0;
printf("请分别输入a,n的值:");
scanf("%d,%d", &a, &n);
for (i = 1; i <= n; i++) {
Tn = Tn + a;
Sn = Sn + Tn;
Tn = 10 * Tn;
}
printf("Sn=%d", Sn);
return 0;
}
运行结果为:
二:Java实现
import java.util.Scanner;
public class SumOfNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入一个数字a:");
int a = input.nextInt();
System.out.print("请输入数字a的位数n:");
int n = input.nextInt();
int sum = 0;
int temp = a;
for (int i = 1; i <= n; i++) {
sum += temp;
temp = temp * 10 + a;
}
System.out.println("Sn = " + sum);
}
}
运行结果: