2017-01-17 4 views
0

私はJavaコースの解決には問題がありますが、私はこの言語を使い慣れていないため、解決策を見つけることができません。誰かが私を助けることができたら嬉しいよ。変数の定義とスイッチの使用

Hは、2.5のような10進値を含む可能性があるため、doubleと定義する必要があります。

現在のコードは完全に動作しますが、Hの整数のみで動作します。私はdouble H = 2.5;で試しましたが、すべてがうんざりです。また、私はintからdoubleへ、あるいはその逆にスイッチを読み、いくつかのコードを試しましたが、スイッチを使用すると、P1 * HP2 * Hが壊れます。

public class PoolTask { 

    public static void main(String[] args) { 

     int V = 200; 
     int P1 = 150; 
     int P2 = 170; 
     int H = 2; 

     int P1w = P1 * H; 
     int P2w = P2 * H; 
     int Pt = P1w + P2w; 

     if (Pt <= V) { 

      int percentage1 = (Pt * 100/V); 
      int percentage2 = (P1w * 100/Pt); 
      int percentage3 = (P2w * 100/Pt); 

      System.out.println("The pool is " + percentage1 + "% full. Pipe 1: " + percentage2 + "%. Pipe 2: " + percentage3 + "%.");    
     } else if (Pt > V) { 

      int liters = (Pt - V); 

      System.out.println("For " + H + " hours the pool overflows with " + liters + " liters"); 
     } else { 
      System.out.println(""); 
     } 
    } 
} 
+2

変更あなたの変数: 'H'、 'P1w'、' P2w'、 'Pt'、' percentage1'、 'percentage2'と' percentage3'にします「ダブル」。 – DimaSan

+2

と 'liters'も同様 –

+0

[可能な二重からintへの可逆変換]の可能な複製(http://stackoverflow.com/questions/26413265/possible-lossy-conversion-from-double-to-int) – DimaSan

答えて

1

に直面している混乱を取り除く:

class PoolTask { 
    public static void main(String[] args) { 
     double V = 200; 
     double P1 = 150; 
     double P2 = 170; 
     double H = 2.0; 

     double P1w = P1 * H; 
     double P2w = P2 * H; 
     double Pt = P1w + P2w; 

     if(Pt <= V) { 
      double percentage1 = (Pt * 100/V); 
      double percentage2 = (P1w * 100/Pt); 
      double percentage3 = (P2w * 100/Pt); 
      System.out.println("The pool is " + percentage1 + "% full. Pipe 1: " + percentage2 + "%. Pipe 2: " + percentage3 + "%.");    
     } else if (Pt > V) { 
      double liters = (Pt - V); 
      System.out.println("For " + H + " hours the pool overflows with " + liters + " liters"); 
     } else { 
      System.out.println(""); 
     } 
    } 
} 

あなたは一例の小数点以下の値で変数を表示したくないしかし、もしあなたはprint文でintにキャストすることができます

System.out.println("The pool is " + (int)percentage1 + ...) 
+0

ありがとう、それは素晴らしい作品:) –

2

doubleのデータ型をHにのみ指定しているためです。 そして、あなたはタイプintの変数にあなたの結果を保存するときは、タイプdoubleのあなたのすべての変数に種類int

宣言の変数のためにそれを保持することはできませんように、他の値で計算した後、その結果は、その端数部分を失いますあなたはあなたがそうのようdoubleにすべての変数を変換することができます

関連する問題