PAT基础编程题目-6-8 简单阶乘计算
程序员文章站
2022-06-08 13:14:35
...
PAT基础编程题目-6-8 简单阶乘计算
题目详情
解答
C语言版
#include <stdio.h>
int Factorial(const int N);
int main()
{
int N, NF;
scanf("%d", &N);
NF = Factorial(N);
if (NF) printf("%d! = %d\n", N, NF);
else printf("Invalid input\n");
return 0;
}
int Factorial(const int N) {
int product = 1;
if (N >= 0) {
for (int i = 2; i <= N; i++)
product = product * i;
return product;
}
return 0;
}
C++版
#include<iostream>
using namespace std;
int Factorial(const int N);
int main() {
int N, NF;
cin >> N;
NF = Factorial(N);
if (NF) cout << N<<"! = " << NF<<endl;
else cout << "Invalid input"<<endl;
return 0;
}
int Factorial(const int N) {
int product = 1;
if (N >= 0) {
for (int i = 2; i <= N; i++)
product = product * i;
return product;
}
return 0;
}
Java版
public class Main{
private static int Factorial(final int N) {
int product = 1;
if(N>=0) {
for (int i = 2; i <= N; i++) {
product = product*i;
}
return product;
}
return 0;
}
public static void main(String[] args) {
int N=0,NF=0;
Scanner scanner = new Scanner(System.in);
if(scanner.hasNext()) {
N = scanner.nextInt();
}
scanner.close();
NF = Factorial(N);
if(NF>0)
System.out.println(N+"!="+NF);
else {
System.out.println("Invalid input");
}
}
}
创作不易,喜欢的话加个关注点个赞,谢谢谢谢谢谢!
上一篇: 我想要个弹窗登录