私は大学でJavaについて学んでいます。私はこのメソッドを印刷しようとしていますThe product of non-negatives = 21
とThe product of negatives = 10
しかし、私は21と10の代わりに両方とも0になっています。私は1つの方法を使って両方の計算を完了することができます。なぜそれは0に等しいですか?ありがとう。1つのJavaメソッドで負の整数と正の整数の積を求めます。回答は印刷されています0
public class Numbers {
public static void main(String[] args) {
int num1 = -2, num2 = 3, num3 = 7, num4 = -5;
findPosNegProd(num1, num2, num3, num4);
}
public static void findPosNegProd(int n1, int n2, int n3, int n4){
int positives = 0;
int negatives = 0;
if(n1 > 0) positives *= n1;
if(n2 > 0) positives *= n2;
if(n2 > 0) positives *= n3;
if(n3 > 0) positives *= n3;
{
if(n1 < 0) negatives *= n1;
if(n2 < 0) negatives *= n2;
if(n2 < 0) negatives *= n3;
if(n3 < 0) negatives *= n3;
}
System.out.println("The product of non-negatives = " + positives);
System.out.println("The product of negatives = " + negatives);
}
}
はあなたが0に初期化し、あなたと掛けているので、それ –
に乗じてきています結果はゼロでなければなりません。1で初期化しようとします。 –
0の代わりに1を使ってポジティブとネガティブを0に初期化します。 – mhasan