0304「三角柱の体積を求めよう」

今回やりたいこと


例題

たかしくんは、三辺の長さがそれぞれ a, b, c である三角形を底面とする、高さが h の三角柱である。
たかしくんは自分の体積が知りたい。

a, b, c, h の順で標準入力に入力したとき、体積を計算し、その結果を標準出力に出力するプログラムを作成しなさい。


要件

  • a, b, c, h はすべて正の整数であるとする
  • 計算結果は全体を左詰めで小数点以下2桁まで出力する
  • 入力した a, b, c から底面が三角形にならない場合、「Error」を標準出力に出力する



実行例1

標準入力
3
9
8
10
標準出力
118.32



実行例2

標準入力
7
1
1
9
標準出力
Error


サンプルコード

import java.util.Arrays;
import java.util.Scanner;

public class Ex_03_04 {

	public static void main(String[] args) {
		// 入力
		Scanner scan = new Scanner(System.in);
		int a = scan.nextInt();	// 辺 a
		int b = scan.nextInt();	// 辺 b
		int c = scan.nextInt();	// 辺 c
		int h = scan.nextInt();	// 高さ h

		// 底面が三角形であるか判定
		int[] sides = {a, b, c};
		Arrays.sort(sides);
		if(sides[2] >= sides[1]+sides[0]) {
			System.out.println("Error");
			return;	// 以降の処理を行わない
		}

		// 計算
		double s = (double) (a+b+c)/2;
		double bottomArea = Math.sqrt(s*(s-a)*(s-b)*(s-c));	// 底面積
		double volume = bottomArea*h;				// 体積

		// 出力
		System.out.printf("%.2f", volume);
	}

}


解説

Arrays

配列を操作するときに使用するクラスです。
java.util.Arrays の import が必要になります。

Arrays.sort(int[] a)

a の要素を昇順にソートするメソッドです。

プログラム例
/* ~~~ 前略 ~~~ */
int[] array = {2, 0, 0, 5, 3, 3, 4};
System.out.println("ソート前: " + Arrays.toString(array));

Arrays.sort(array);
System.out.println("ソート後: " + Arrays.toString(array));
/* ~~~ 後略 ~~~ */
実行結果
ソート前: [2, 0, 0, 5, 3, 3, 4]
ソート後: [0, 0, 2, 3, 3, 4, 5]


応用

h を1で固定すると三角形の面積を求めるプログラムになってしまいますね!