我收到了那个任务: 》编写一个小方法,calculateProduct。它会要求用户输入两个int值,然后计算并显示输入的两个值之间所有值的乘积。例如,如果用户输入数字2和5程序将显示结果120(计算为2 * 3 * 4 * 5)”
我尝试构建这样的东西:
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。有人知道如何修复它吗?谢谢!
最佳答案
将循环更改为:
for (int i = small + 1; i <= big; i++)
{
result *= i;
}
关于java:如何计算变量差值中所有值之间的乘法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39953552/