[java] Raising a number to a power in Java

Here is my code. For some reason my BMI is not calculated correctly. When I check the output on a calculator for this : (10/((10/100)^2))) I get 1000, but in my program, I get 5. I'm not sure what I am doing wrong. Here is my code:

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);
    }
}

This question is related to java

The answer is


we can use

Math.pow(2, 4);

this mean 2 to the power 4 (2^4)

answer = 16


Your calculation is likely the culprit. Try using:

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

Because both height and 100 are integers, you were likely getting the wrong answer when dividing. However, 100.0 is a double. I suggest you make weight a double as well. Also, the ^ operator is not for powers. Use the Math.pow() method instead.


You should use below method-

Math.pow(double a, double b)

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


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);

1) We usually do not use int data types to height, weight, distance, temperature etc.(variables which can have decimal points) Therefore height, weight should be double or float. but double is more accurate than float when you have more decimal points

2) And instead of ^, you can change that calculation as below using Math.pow()

bmi = (weight/(Math.pow(height/100, 2)));

3) Math.pow() method has below definition

Math.pow(double var_1, double var_2);

Example:

i) Math.pow(8, 2) is produced 64 (8 to the power 2)

ii) Math.pow(8.2, 2.1) is produced 82.986813689753 (8.2 to the power 2.1)


^ is not the operator you want. You are looking for the pow function of java.lang.Math.

You can use Math.pow(value, power).

Example:

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

Too late for the OP of course, but still... Rearranging the expression as:

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

Eliminates all the floating point, and converts a division by a constant to a multiplication, which should execute faster. Integer precision is probably adequate for this application, but if it is not then:

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

would still be an improvement.