題目:求s=a+aa+aaa+aaaa+aa...a的值,其中a是一個數字。例如2+22+222+2222+22222(此時共有5個數相加),幾個數相加有鍵盤控制。
程序分析:關鍵是計算出每一項的值。
程序設計:
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個數相加的值的實現代碼,需要的朋友可以參考一下。