【问题标题】:How can I get the proper factorial numbers of the user inputs?如何获得用户输入的正确阶乘数?
【发布时间】:2022-12-04 00:59:36
【问题描述】:

我想正确获取用户输入的每个数字的阶乘。第一个输入的阶乘是正确的,但下一个输入的阶乘是不正确的。

这就是我得到的:the output of my code

输出/阶乘应该是这样的:correct factorial of numbers

这是我的代码:

public class Factor {
    public static void main(String[] args) {
        Scanner type = new Scanner(System.in);
    
    int i, fact = 1;
    System.out.println("<------ FACTORIAL CALCULATOR ------>");
    
    while (true) {
        System.out.print("Enter a positive integer: ");
        int num = type.nextInt();
        
        
        if (num > 0) {
            System.out.print(num + "! = ");
            
            for (i = 1; i <= num; i++) {
                System.out.print(i);
                
                if(i != num) {
                    System.out.print(" x ");    
                }
            }
            for (i = 1; i <= num; i++) {
                fact = fact * i;
            }
            System.out.println("\nThe factorial of " + num + " is: " + fact);
            
        } 
        else {
            System.out.println("Invalid input! Program stopped!");
            break;
        }
        
    }
    
}

}

【问题讨论】:

    标签: java loops while-loop


    【解决方案1】:

    答案很简单,你永远不会在成功一次后重置你的factorial变量。

    只需将 fact 变量声明移动到您的 while 循环中,它就会起作用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      • 2018-04-08
      • 2022-09-27
      • 2016-04-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多