How to find factorial and show result of counting in console?

好久不见. 提交于 2019-12-25 18:31:46

问题


public class Car {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        System.out.println(n+"!="+factorial(n));
    }
    public static int factorial(int num) {
        return (num == 0) ? 1 : num * factorial (num - 1);
    }
}

how make this code to text in console 3! = 1*2*3 = 6?


回答1:


Don't use recursion for this. Besides, it isn't really efficient or necessary.

      Scanner in = new Scanner(System.in);
      int n = in.nextInt();
      int fact = 1;
      String s = n + "! = 1";
      for (int i = 2; i <= n; i++) {
         fact *= i;
         s += "*" + i;
      }
      s += " = ";
      System.out.println(s + fact); 





回答2:


You can do it as follows:

import java.util.Scanner;

public class Car {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter an integer: ");
        int n = in.nextInt();
        StringBuilder strFact=new StringBuilder();
        int fact=factorial(n,strFact);
        strFact.deleteCharAt(strFact.length()-1);
        System.out.println(n + "!= " + strFact+" = "+fact);
    }

    public static int factorial(int num, StringBuilder strFact) {
        int fact;
        if (num == 0) {
            fact = 1;
        }
        else {
            fact = num * factorial(num - 1,strFact);
            strFact.append(num+"*");
        }
        return fact;
    }
}

A sample run:

Enter an integer: 3
3!= 1*2*3 = 6


来源:https://stackoverflow.com/questions/59237611/how-to-find-factorial-and-show-result-of-counting-in-console

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!