I’m trying to calculate BMI in my Java program, but the output seems incorrect. When I check the result with a calculator for this formula:
(10 / ((10 / 100) ^ 2))
I get 1000, but in my program, I get 5.
Here’s my code:
bmi = (weight / ((height / 100) ^ 2)); // Incorrect calculation
It looks like the exponentiation (^2
) isn’t working as expected.
How should I correctly raise a number to a power in Java to fix this issue?
I see where things are going wrong. In Java, the ^ operator does not perform exponentiation—it’s actually a bitwise XOR operator, which explains why your calculation is incorrect.
Don’t worry! There are a few proper ways to raise a number to a power in Java.
Java provides the Math.pow(base, exponent) method, which is the correct way to raise a number to a power.
bmi = (weight / Math.pow((height / 100.0), 2)); // Correct power calculation
Why use this?
Math.pow(x, y) correctly computes x^y. It ensures floating-point division (height / 100.0 instead of height / 100, which would cause integer division).
Since you’re only raising a number to the power of 2, you can simply multiply it by itself instead of using Math.pow().
double heightInMeters = height / 100.0;
bmi = (weight / (heightInMeters * heightInMeters)); // Squaring manually
Why use this?
Faster and more efficient than Math.pow() when squaring.
Avoids unnecessary function calls for a simple exponentiation.
If you need to raise a number to a power without using Math.pow(), you can implement a simple loop-based exponentiation.
public static double power(double base, int exponent) {
double result = 1;
for (int i = 0; i < exponent; i++) {
result *= base;
}
return result;
}
And modify your BMI calculation:
double heightInMeters = height / 100.0;
bmi = (weight / power(heightInMeters, 2)); // Using custom power method
Why use this?
Good learning exercise to understand exponentiation logic.
Can be modified for integer-based exponentiation.