2014年2月20日 星期四

java程式設計題目---公式計算【海龍公式】

Write a program that prompts the user to enter three points ( x1 ,  y1 ) , ( x2 , y2 ) , ( x3 ,  y3) of a triangle and displays its area.

The formula for computing the area of a triangle is:

A = { S * ( S - a ) * ( S - b ) * ( S - c ) } ^ 0.5


設計一個程式讓使用者輸入一三角形的三點座標 ( x1 ,  y1 ) , ( x2 , y2 ) , ( x3 ,  y3) 然後印出其面積。

如果三角形的三邊長為a、b、c,面積為 A,S = ( a + b + c ) / 2, 我們可以得到

A = { S * ( S - a ) * ( S - b ) * ( S - c ) } ^ 0.5


import java.util.Scanner;//Scanner is in the java.util package

public class C1 
{
     public static void main(String[] args) 
     {
  
          // create Scanner object
          Scanner input = new Scanner(System.in);

           // 創建並提示使用者輸入 x1
          System.out.println("Enter a number for x1");
          double x1 = input.nextDouble();

           // 創建並提示使用者輸入 y1
          System.out.println("Enter a number for y1");
          double y1 = input.nextDouble();

           // 創建並提示使用者輸入 x2
          System.out.println("Enter a number for x2");
          double x2 = input.nextDouble();

           // 創建使用者輸入 y2
          System.out.println("Enter a number for y2");
          double y2 = input.nextDouble();

           //創建並提示使用者輸入 x3
          System.out.println("Enter a number for x3");
          double x3 = input.nextDouble();

           // 創建並提示使用者輸入 y3
          System.out.println("Enter a number for y3");
          double y3 = input.nextDouble();

           // 計算 side1
          double a1 = ( x2 - x1 ) * ( x2 - x1 );
          double a2 = ( y2 - y1 ) * ( y2 - y1 );
          double a3 = a1 + a2;
          double side1 = (Math.pow( a3 , 0.5 ));

           // 計算 side2
          double b1 = ( x3 - x2 ) * ( x3 - x2 );
          double b2 = ( y3 - y2 ) * ( y3 - y2 );
          double b3 = b1 + b2;
          double side2 = (Math.pow( b3 , 0.5 ));

           // 計算 side3
          double c1 = ( x1 - x3 ) * ( x1 - x3 );
          double c2 = ( y1 - y3 ) * ( y1 - y3 );
          double c3 = c1 + c2;
          double side3 = (Math.pow( c3 , 0.5 ));
  
          //計算 S
          double s = ( side1 + side2 + side3 ) / 2;
  
          //計算 a,b,c,d
          double a = s - side1;
          double b = s - side2;
          double c = s - side3;
          double d = s * a * b * c;
  
          //計算 area
          double area = (Math.pow( d , 0.5 ));
  
          /顯示運算結果
          System.out.println("(" + x1 + "," + y1 + ")"  + 
               "(" + x2 + "," + y2 + ")"  +
               "(" + x3 + "," + y3 + ")"  + 
               "面積是"+ area ); 
     }
}

Go(Golang)程式語言 設定GCC

下載MSYS2:  https://www.msys2.org/ 安裝 程式開始執行後輸入: pacman -Syu y y 在安裝目錄底下找到msys2.exe,雙擊執行 輸入指令: pacman -Su pacman -S --needed base-devel mingw-...