Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raising a number to a power in Java

Tags:

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);     } } 
like image 859
stytown Avatar asked Jan 12 '12 21:01

stytown


1 Answers

^ in java does not mean to raise to a power. It means XOR.

You can use java's Math.pow()


And you might want to consider using double instead of int—that is:

double height; double weight; 

Note that 199/100 evaluates to 1.

like image 89
WuHoUnited Avatar answered Sep 27 '22 20:09

WuHoUnited