program story

Java에서 숫자를 거듭 제곱하기

inputbox 2020. 12. 3. 07:48
반응형

Java에서 숫자를 거듭 제곱하기


다음은 내 코드입니다. 어떤 이유로 내 BMI가 올바르게 계산되지 않습니다. 계산기에서 출력을 확인하면 (10/((10/100)^2)))1000 점을 얻었지만 프로그램에서는 5 점을 얻었습니다. 제가 뭘 잘못하고 있는지 잘 모르겠습니다. 내 코드는 다음과 같습니다.

import javax.swing.*;

public class BMI {
    public static void main(String args[]) {
        int height;
        int weight;
        String getweight;
        getweight = JOptionPane.showInputDialog(null, "Please enter your weight in Kilograms");
        String getheight;
        getheight = JOptionPane.showInputDialog(null, "Please enter your height in Centimeters");
        weight = Integer.parseInt(getweight);
        height = Integer.parseInt(getheight);
        double bmi;
        bmi = (weight/((height/100)^2));
        JOptionPane.showMessageDialog(null, "Your BMI is: " + bmi);
    }
}

^자바에서 권력을 올리는 것을 의미하지는 않습니다. XOR을 의미합니다.

Java를 사용할 수 있습니다. Math.pow()


다음과 같이 double대신 사용하는 것이 좋습니다 int.

double height;
double weight;

참고 199/1001로 평가합니다.


우리는 사용할 수 있습니다

Math.pow(2, 4);

이것은 2의 거듭 제곱 4 (2 ^ 4)를 의미합니다.

답변 = 16


귀하의 계산이 범인 일 수 있습니다. 다음을 사용해보십시오.

bmi = weight / Math.pow(height / 100.0, 2.0);

height둘 다 100정수 이기 때문에 나눌 때 잘못된 답을 얻었을 가능성이 있습니다. 그러나 100.0이중입니다. 나는 당신도 weight더블을 할 것을 제안합니다 . 또한 ^운영자는 권력을위한 것이 아닙니다. Math.pow()대신 방법을 사용하십시오 .


^원하는 연산자가 아닙니다. pow기능을 찾고 java.lang.Math있습니다.

사용할 수 있습니다 Math.pow(value, power).

예:

Math.pow(23, 5); // 23 to the fifth power

물론 OP에는 너무 늦었지만 여전히 ... 표현식을 다음과 같이 재정렬합니다.

int bmi = (10000 * weight) / (height * height)

모든 부동 소수점을 제거하고 상수에 의한 나눗셈을 곱셈으로 변환하므로 더 빨리 실행됩니다. 정수 정밀도는이 응용 프로그램에 적합 할 수 있지만 그렇지 않은 경우 :

double bmi = (10000.0 * weight) / (height * height)

여전히 개선 될 것입니다.


int weight=10;
int height=10;
double bmi;
bmi = weight / Math.pow(height / 100.0, 2.0);
System.out.println("bmi"+(bmi));
double result = bmi * 100;
result = Math.round(result);
result = result / 100;
System.out.println("result"+result);

아래 방법을 사용해야합니다.

Math.pow (더블 a, 더블 b)

Returns the value of the first argument raised to the power of the second argument.

참고URL : https://stackoverflow.com/questions/8842504/raising-a-number-to-a-power-in-java

반응형