嗨我正在大学学习java,我刚刚完成了一段计算BMI的代码,就像这样,num1是千克,num2是厘米((num1 / num2)/ num2)* 10000 ; 当我向老师展示这个等式时,他告诉我这是不正确的,正确的是 num1 /((num2 * num2)/ 10000); 当我测试两行代码时得到了相同的结果,但他告诉我,我需要证明两条线都像AxB和BxA一样,但是我没有找到方法来证明它们是相同的,但我确实知道它们是如何' d是一样的。我的问题是,它们都是一样的吗?
如果我将70 KG作为体重,将175 CM作为身高,那么它会说出22.9的线条(记住这是我的等式)。和我的老师一样,它会是一样的。但他不相信他们是一样的。这是我的代码:
import javax.swing。*; import java.util.Scanner;
class apples {
public static void main (String args[]) {
String fsum; /* this is a variable declaration*/
String sum; /* this is a variable declaration*/
double answer; /* this is a variable declaration*/
double num1, num2; /* this is a variable declaration*/
String anything; /* this is a variable declaration*/
Scanner Tahmid = new Scanner (System.in);/*Scanner Variable*/
System.out.println("This program was created by Tahmid Ahmed on 01/10/2013\nThis program would allow you the user to be able to calculate your BMI");
System.out.println("To continue please click enter");/*Output*/
anything = Tahmid.nextLine();/*Input as a break*/
fsum=JOptionPane.showInputDialog("Please enter weight in Kilograms (KG) " ); /*Popup box to allow weight to be entered*/
sum=JOptionPane.showInputDialog("Please enter height in Centimetres (CM) ");/*Popup box to allow height to be entered*/
num1 = Double.parseDouble(fsum);/*Conversion of String into Double*/
num2 = Double.parseDouble(sum);/*Conversion of String into Double*/
answer = num1/((num2*num2)/10000);/*<<<<<<<<-----My teachers Equation*/ /*My Equation ---- >>>>>> ((num1/num2)/num2)*10000 */
if (answer<=18){
JOptionPane.showMessageDialog(null, "Your total BMI levels are: " + answer, "You're underweight! Eat some more!", JOptionPane.INFORMATION_MESSAGE);
}
else if(answer>=25){
JOptionPane.showMessageDialog(null, "Your total BMI levels are: " + answer, "You're overweight now bro! Eat Less!", JOptionPane.INFORMATION_MESSAGE); }
else if(answer<25) {
JOptionPane.showMessageDialog(null, "Your total BMI levels are: " +answer, "You're the perfect weight! Stay that way :)", JOptionPane.INFORMATION_MESSAGE);}
}
}
答案 0 :(得分:2)
它们在数学上是等价的,但在浮点数上不等效。你的老师试图指出所有的乘法应该在所有的分割之前进行,这样才能达到最大的精度。 num2*num2
周围的括号确保首先计算它。
答案 1 :(得分:1)
只要玩代数,很明显它们是等价的:
((num1/num2)/num2)*10000 ?? num1/((num2*num2)/10000)
((num1/num2) * (1/(num2)) * 10000 ?? num1 / (num2^2 / 10000)
(num1 / num2^2) * 10000 ?? num1 * (10000 / num2^2)
10000 * num1 / num2^2 == 10000 * num1 / num2^2