题目:a+aa+aaa+.......+aaaaaaaaa,其中a为1至9之中的一个数,项数也要可以指定。
代码
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入a:");
int a = sc.nextInt();
System.out.println("请输入项数:");
int count = sc.nextInt();
int res = 0;
int temp = 0;
for (int i = 0; i < count; i++) {
if (i == 0) {
temp = a;
res += temp;
} else {
temp = temp * 10 + a;
res += temp;
}
}
System.out.println("结果:" + res);
}
}
自我理解如下:
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入a:");
int a = sc.nextInt();
System.out.println("请输入项数:");
int count = sc.nextInt();
这一段是java的输入函数,可以看作者的另一篇笔记。
int res = 0; //定义一个变量作为总和
int temp = 0; //定义一个变量作为当前值,便于计算
for (int i = 0; i < count; i++) {
if (i == 0) { //当项数为0时,算式总和为a。
temp = a;
res += temp;
} else { //当项数不为0时,将每一项加起来
temp = temp * 10 + a; //temp计算的是当前项的值。
res += temp;
}
设a=1,i=1时,temp=1*10+1=11;
i=2时,temp=11*10+1=111;
......
如此,便可以一直计算,直到将给出的项数相加完,得出答案。
}
System.out.println("结果:" + res);
}
}