題目:求s=a+aa+aaa+aaaa+aa...a的值,其中a是一個(gè)數(shù)字。例如2+22+222+2222+22222(此時(shí)共有5個(gè)數(shù)相加),幾個(gè)數(shù)相加有鍵盤控制。
程序分析:關(guān)鍵是計(jì)算出每一項(xiàng)的值。
程序設(shè)計(jì):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
import java.io.*; public class Sumloop { public static void main(String[] args) throws IOException { int s= 0 ; String output= "" ; BufferedReader stadin = new BufferedReader( new InputStreamReader(System.in)); System.out.println( "請輸入a的值" ); String input =stadin.readLine(); for ( int i = 1 ;i<=Integer.parseInt(input);i++) { output+=input; int a=Integer.parseInt(output); s+=a; } System.out.println(s); } } |
另解:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
import java.io.*; public class Sumloop { public static void main(String[] args) throws IOException { int s= 0 ; int n; int t= 0 ; BufferedReader stadin = new BufferedReader( new InputStreamReader(System.in)); String input = stadin.readLine(); n=Integer.parseInt(input); for ( int i= 1 ;i<=n;i++){ t=t* 10 +n; s=s+t; System.out.println(t); } System.out.println(s); } } |
以上就是Java求s=a+aa+aaa+aaaa+aa...a 5個(gè)數(shù)相加的值的實(shí)現(xiàn)代碼,需要的朋友可以參考一下。