2016-06-24 12 views
2

これは動作するコードですが、私はJavaで整数と倍数を掛けることについての完全な研究の後に疑問を抱いています。なぜコードの下のスニペットがエラーを出すのかまだ分かりません。助けてください?intに括弧を追加し、javaにdoubleを追加するとエラーが発生する理由は?

public class Arithmetic { 

    public static void main(String[] args) { 
     Scanner scan = new Scanner(System.in); 
     double mealCost = scan.nextDouble(); // original meal price 
     int tipPercent = scan.nextInt(); // tip percentage 
     int taxPercent = scan.nextInt(); // tax percentage 
     scan.close(); 

     // Calculate Tax and Tip: 
     double tip = mealCost * tipPercent/100; //HERE IS MY PROBLEM 
     double tax = mealCost * taxPercent/100; //HERE IS MY PROBLEM 

     // cast the result of the rounding operation to an int and save it as totalCost 
     int totalCost = (int) Math.round(mealCost + tax + tip); 

     System.out.println("The total meal cost is " + totalCost + " dollars."); 
    } 
} 

この回答がより論理的で、上記とは異なる値を示していることを知っていますか?あなたの第1の例で

double tip = meal * (tipPercent/100); 
double tax = meal * (taxPercent/100); 

答えて

2

、乗算が正しい二重結果を与える、100で除算され、二重数で、その結果、最初に実行されます。あなたの第2バージョンにおいて

mealCost * tipPercent/100; 

を、整数除算が最初に実行され、結果が整数になります。 tipPercentが100未満であると仮定すると、結果はゼロになります。のは、想像してみましょう

double tip = meal * (tipPercent/100.0); 
1

int tipPercent = 10; 
double mealCost = 100.123d; 

そして

double tip = mealCost * tipPercent/100; 


1. 100.123

を(あなたがより良い番目のバージョンのような場合は

は、単に一定の浮動小数点を使用しますdouble)* 10(第0)= 1001.23(double
2. 1001.23(double)/ 100(int)= 10.0123(double

double tip = mealCost * (tipPercent/100); 
  1. 10(int)/ 100( int)= 0(int
  2. 100.123(double)* 0 = 0(double
関連する問題