我接到這個任務: 「小法,calculateProduct要寫到它會要求用戶輸入兩個int值,然後計算並顯示產品。例如,如果用戶輸入數字2和5,則程序將顯示結果120(計算爲2 * 3 * 4 * 5)「的java:如何計算的所有值之間的乘法變量差異
我試圖構建類似於這個:
import java.util.Scanner;
public class Exam {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a;
int b;
int big;
int small;
//ask to insert two variables
System.out.println("Insert variable a");
a = in.nextInt();
System.out.println ("Insert variable b");
b=in.nextInt();
// compare two variables
// set the biggest variables to b, the smallest - to a
if (a >=b){
big=a;
small=b;
}
else {
big=b;
small=a;
}
// set the do while loop to complete the code. Run multiplying before counter won't fit to b variable
int result = small;
for (int i=small; i<=big;i++){
result*=i;
}
System.out.println("the multiplication progression between "+small+" and "+big+" equals to "+result);
}
}
但是,當我插入2和5時,結果是240.有人知道如何解決它嗎?謝謝!
將'result'初始化爲'1'而不是'small'。 – jsheeran
你乘以'小'兩次。 –