问题描述
求Sn=a+aa+aaa+aaaa+aaaaa
代码实现
#include<stdio.h>
int main()
{
int a = 0;
int Sn = 0;
scanf("%d", &a);
Sn = (5 * a) + (4 * a * 10) + (3 * a * 100) + (2 * a * 1000) + (a * 10000);//由于数据较小,容易总结规律,但不具有普遍性
printf("Sn=%d\n", Sn);
return 0;
}
运行结果
代码改进
#include<stdio.h>
int main()
{
int i = 0;
int a = 0;
int n = 0;
int Sn = 0;
int tmp = 0;//每一项的数值
scanf("%d", &a);//a的数值
scanf("%d", &n);//前n项
for (i = 0; i <n; i++)
{
tmp = tmp * 10 + a;//后一项等于前一项*10+a
Sn += tmp;
}
printf("Sn=%d\n", Sn);
return 0;
}
运行结果