Java Coding 編程系列: 初級篇之一 求BMI Math.pow Math.round

Java Coding 編程系列: 初級篇之一 求BMI Math.pow Math.round

將會有一系列 Java Coding 編程系列: 初級篇推出
求BMI
請注意Height是Meter,如果給的單位是CM,要Height/100.0 

1. 介紹Math.pow 用法: 

Java 的MATH method , 有很多用處,Math.pow是其中之一。

int number = (int) Math.pow(3, 4);

這個意思是求3的4次方。

所以用在BMI,就是Math.pow(Height,2) , 即是求Height 的二次方。

2. 介紹Math.round 用法:

把數目的小數點四捨五入:
double d =。63.67;
         System.out.println(Math.round(d));
結果是64

2. 如果想在介面輸入數字,可用Scanner Class 方法:

在CODING 開首 打入import java.util.Scanner;
(即是引入Scanner Class)

這樣就能通過介面輸入打入所需資料
int 相應的是nextInt()
double 相應的是nextDouble()

Coding: 

import java.util.Scanner;

public class Number {
  public static void main(String[] args) {
    int weight;
    double height;
    double BMI;
    double heighta;

    Scanner myObj = new Scanner(System.in);
    System.out.println("Enter your weight(kg)");
    weight = myObj.nextInt();

    System.out.println("Weight is: " + weight);

    System.out.println("Enter your height(cm)");
    height = myObj.nextDouble();

    System.out.println("Height is: " + height);
    heighta = height / 100.0;

    BMI = weight / Math.pow(heighta, 2);

    System.out.println("BMI is" + Math.round(BMI));
  }

}

試一下: 
假設weight是60kg, height是150cm: 

Result: 
Enter your weight(kg)
60
Weight is: 60
Enter your height(cm)
150
Height is: 150.0
BMI is 27



留言

這個網誌中的熱門文章

如何設定Google Form顯示語言 Display language 是某一種特定語言Particular Language ?

壞機救資料神器Hiren’s BootCD PE (免費軟件) - Boot Failure ? Scan Virus 先

Adobe Ai 外框outline 是什麼?轉了外框要再更改,後悔怎麼辦?