题目描述
求 s=a+aa+aaa+aaaa+aa…a 的值,其中 a 是一个数字,例如:2+22+222+2222+22222 (此时共有5个数相加),几个数相加由键盘控制。
程序分析:关键是计算出每一项的值
输入
输入每一项的基础数字及相加的项数,中间用空格隔开
输出
输出序列和
样例输入
2 5
样例输出
24690
源代码
#include <stdio.h>
int main() {
int sum = 0; // 存储结果的变量
int base, terms; // base 为 a 的值,terms 为 n 的值
int temp; // 临时变量,用于计算当前项的值
scanf("%d%d", &base, &terms);
temp = base; // 初始化 temp 为 a
// 通过循环计算 a + aa + aaa + ...
while (terms > 0) {
sum += temp; // 累加当前项
base *= 10; // base 每次左移一位(例如 2 -> 20 -> 200)
temp += base; // 更新 temp,使其变为下一项
terms--; // 减少剩余项数
}
printf("%d\n", sum);
return 0;
}