課題3

課題内容

 

    * Report#3:体積・表面積公式クラスの作成{〜12/11(Mon)}
          o (1)3種以上の体積を求めるクラスを作成し、具体的な値を入力しプ
          ログラムを実行せよ。
          o (2)2種以上の表面積を求めるクラスを作成し、同様に実行せよ。
          o (3)例題を参考に、階乗計算を再帰プログラムにより作成し、for文
          による階乗計算との違いを考察せよ。
          o  例題:階乗計算:for文&再帰呼び出し
          o 課題のWebページは、必ず別のスタイルシートファイルを用いるこ
          と。 

(1)3種以上の体積を求めるクラスを作成し、具体的な値を入力しプログラムを 実行せよ。


(1)のソースプログラム


class Point3D {
    double x;
    double y;
    double z;

    Point3D(double x) {
        this.x = x;
    }

    Point3D(double x,double y,double z) {
        this.x = x;
        this.y = y;
        this.z = z;
    }

}

class volume {
    public static void main(String args[]) {
        Point3D p1 = new Point3D(1.1,1.1,1.1);
        double answer1 = p1.x*p1.y*p1.z;
        System.out.println("Volume1 = " + answer1);
        Point3D p2 = new Point3D(2.2);
        double answer2 = Math.pow(p2.x,3);
        System.out.println("Volume2 = " + answer2);
        Point3D p3 = new Point3D(Math.PI,3.3,3.3);
        double answer3 = p3.x*Math.pow(p3.y,2)*p3.z;
        System.out.println("Volume3 = " + answer3);
    }
}

実行結果


Volume1 = 1.3310000000000004
Volume2 = 10.648000000000003
Volume3 = 112.89941519205637

(1)の考察



(2)2種以上の表面積を求めるクラスを作成し、同様に実行せよ。


(2)のソースプログラム


class Detail {
    double p = Math.PI;
    double r;
    double h;

    Detail(double r) {
        this.r = r;
    }
    Detail(double r,double h) {
        this.r = r;
        this.h = h;
    }
}

class Area {
    public static void main(String args[]) {
        Detail a = new Detail(2);
        double answer1 = 4*a.p*Math.pow(a.r,2);
        System.out.println("Area1 = " + answer1);

        Detail b = new Detail(4,4);
        double answer2 = 4*(0.5*b.r*b.h);
        System.out.println("Area2 = " + answer2);
    }
}

実行結果


Area1 = 50.26548245743669
Area2 = 32.0

(2)の考察



(3)例題を参考に、階乗計算を再帰プログラムにより作成し、for文による階乗計 算との違いを考察せよ。


(3)のソースプログラム


import java.io.*;

class Recursive {
    public static void main(String args[]) throws Exception {

        BufferedReader in = new BufferedReader(new
        InputStreamReader(System.in)\);

        System.out.print("input natural number: ");
        int num = (new Integer(in.readLine())).intValue();

        System.out.print("再帰呼び出しによる階乗計算 => ");
        System.out.println(num + "!=" + detail(num));

    }

    static int detail(int n) {
        if(n == 0) return(1);
        return detail(n-1)*n;
    }
}

実行結果


input natural number: 5
再帰呼び出しによる階乗計算 => 5!=120

(3)とFOR文の階乗計算との違いの考察



感想