代码如下:
#include <stdio.h>
int main() {
int a = 2; // 数字a
int n = 10; // 项数n,可以根据需要修改
int term = 0; // 当前项
int s = 0; // 累加和s
// 循环计算每一项并累加
for (int i = 1; i <= n; i++) {
term = term * 10 + a; // 构造当前项,例如2, 22, 222...
/*
i = 1时
term = 0 * 10 + 2 2
i = 2时
term = (0 * 10 + 2 ) * 10 + 2 22
i = 3时
term = ((0 * 10 + 2 ) * 10 + 2) * 10 + 2 222
...
...
*/
s += term; // 累加当前项到s 求和
}
// 输出结果
printf("当n=%d时,s的值为:%d\n", n, s);
return 0;
}