析因问题

Factorial Issue

我是编码新手 Java,但我需要编写一个从整数 1 到 n 的程序。该程序会要求用户输入一个正数,如果不是正数,则会要求输入另一个数字。

在程序中为 n 输入正整数后,它会显示如何计算第 n 个阶乘以及结果。

所以我的程序将显示除结果之外的所有内容,它不是将所有数字相乘。如果有人能指出正确的方向来解决这个问题,那就太好了!

代码:

import java.util.Scanner;
public class Problem5 {
   public static void main(String[] args){

   int n, i =1;
   Scanner kbd = new Scanner(System.in);

   System.out.print("Enter n: ");
   n = kbd.nextInt();

   while (n <= 0) {
      System.out.print("Enter n: ");
       n = kbd.nextInt();
   }
   for (i = 1; i <= n; i++){
      System.out.print( i+ "*");
   }

   System.out.print(" is " + n * i);

   }
}

输出:

输入n: 5 1*2*3*4*5* 是 30


如您所见,结果应该是 120 而不是 30。

只是改变那个部分

for (i = 1; i <= n; i++){
   System.out.print( i+ "*");
}

System.out.print(" is " + n * i);

int result = 1;
for (i = 1; i <= n; i++){
   System.out.print( i+ "*");
   result *= i;
}

System.out.print(" is " + result);

你最后一次打印是错误的,因为你只是将 n 与 i 相乘,这是一个简单的乘法,与阶乘无关。

您的程序只进行一次计算(“是”+ n * i),并且此计算不进行阶乘。您可能想多次执行乘法运算 - 并且使用不同的数字。

你没有正确计算。您只需显示 n*i` 的最终结果。

在下面的解决方案中,我采用了 int fact = 1 并将其与 for 循环内的 i 的值相乘,并将结果分配回 fact多变的。这是核心部分。这就是你如何获得 1*2*3...*n = n!

import java.util.Scanner;
public class SomeArrayQuestion {
    public static void main(String[] args) {

        int n, i = 1;
        Scanner kbd = new Scanner(System.in);

        System.out.print("Enter n: ");
        n = kbd.nextInt();

        while (n <= 0) {
            System.out.print("Enter n: ");
            n = kbd.nextInt();
        }
        int fact = 1;
        for (i = 1; i <= n; i++) {
            System.out.print(i + "*");
            fact = fact * i;
        }

        System.out.print(" is " + fact);

    }
}
import java.util.Scanner;
public class Problem5 {
   public static void main(String[] args){

   int n, i =1;
   Scanner kbd = new Scanner(System.in);

   System.out.print("Enter n: ");
   n = kbd.nextInt();

   while (n <= 0) {
      System.out.print("Enter n: ");
       n = kbd.nextInt();
   }
   int result = 1;
   for (i = 1; i <= n; i++){
      System.out.print( i+ "*");
      result *= i;
   }

   System.out.print(" is " + result);

   }
}

Output:
    Enter n: 5
    1*2*3*4*5* is 120