所以我回来了一个新的问题,如下: 我需要计算用户输入的阶乘,现在我的问题是我找不到任何代码或解释如何做这样的事情,我也看到了Stackoverflow上的一个主题,但它对我没有任何帮助我不知道从哪里开始我唯一拥有以下内容:
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String invoer;
System.out.print("Fill in a Number:");
invoer = br.readLine();
}
所以这并不多,我希望你们能帮助我!
亲切的问候, MIKEY
答案 0 :(得分:2)
用于计算来自用户的阶乘给定输入数的代码:
import java.util.Scanner;
class Factorial
{
public static void main(String args[])
{
int n, c, fact = 1;
System.out.println("Enter an integer to calculate it's factorial");
Scanner in = new Scanner(System.in);
n = in.nextInt();
if ( n < 0 )
System.out.println("Number should be non-negative.");
else
{
for ( c = 1 ; c <= n ; c++ )
fact = fact*c;
System.out.println("Factorial of "+n+" is = "+fact);
}
}
}
OR 以更加模块化的方式
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number whose factorial is to be found: ");
int n = scanner.nextInt();
int result = factorial(n);
System.out.println("The factorial of " + n + " is " + result);
}
public static int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result = result * i;
}
return result;
}
}
答案 1 :(得分:1)
static int factorial(int n){
return n == 0 ? 1 : (n * factorial(n-1));
}
答案 2 :(得分:1)
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
System.out.println("Enter No : ");
int n=sc.nextInt();
int fact=1;
if(n>0)
{
for(int i=1;i<=n;i++)
fact *= i;
System.out.println("Factorial of "+n +" is = "+fact);
}
else
{
System.out.println("Invalid Input");
}
}
}
答案 3 :(得分:0)
这看起来像是我的作业。您可以将此问题分解为以下问题,并按此顺序解决它们:
int
的{{3}}的函数。处理边缘情况,例如何时n < 1
。使用各种输入从main
调用它。Scanner
。Sytem.out.println()
将结果写入标准输出。