目次> 第20章> 20.1 | TOPUPPREVNEXT |
int fact = 1; for(int i=1; i<=10; i++) fact = fact * i;ですね。
public class Factx{ public static void main(String arg[]) { if(arg.length == 1) { int x = Integer.parseInt(arg[0]); int fact = 1; for(int i=1; i<=x; i++) fact *= i; System.out.println(x + "! = " + fact); } else { System.out.println("use as: java Factx 10"); } } }
メソッドの書き方で書くと
static int fact(int n) { if(n==1) return 1; else return n * fact(n-1); }となる。先ほどのプログラムを書直して実行してみてください。
public class Facty{ public static void main(String arg[]) { if(arg.length == 1) { int x = Integer.parseInt(arg[0]); System.out.println(x + "! = " + fact(x)); } else { System.out.println("use as: java Facty 10"); } } static int fact(int n) { if(n==1) return 1; else return n * fact(n-1); } }
いけてる、いけてる。
階乗の計算がすすむ様子をみてみましょう。下の TextField に12以下の数字を
いれて、「デモ開始」ボタンをクリックしてください。
上図を表示するプログラムは、 ソースプログラム factap2.java にあります。
このプログラムをよびだす HTMLファイルは こちら です。
更新日:2004-12-10 | TOPUPPREVNEXT |