java:如何计算变量差值中所有值之间的乘法

标签 java

我收到了那个任务: 》编写一个小方法,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/

相关文章:

java - 一种检查 servlet 是否已经在处理的方法 - j2ee?

java - 你能证明Hibernate延迟加载吗?

java - LibGDX:特殊字符不会显示

java - JUnit 测试收到 UnfinishedStubbingException

Java 反射 : Checking the type of the method parameter at runtime

java - 在应用服务器上部署多个应用程序(weblogic/websphere)

java - 变量名在接口(interface)声明中有何用处?

关于捕获组的java正则表达式问题

java - 使用 lambda 表达式中的参数调用构造函数

java - puppetlabs-java Oracle 无法应用目录 : No title provided and :file is not a valid resource reference