程序应该询问用户是否为正整数并打印析因表。如果输入小于0,则输出或程序应该停止。
给我一个正整数:5
输出:
5! = 5 x 4 x 3 x 2 x 1
阶乘5是120
给我一个正整数:-5
输出:输入无效!程序停止
P.s:我是初学者。我正在使用Netbean IDE
这应该工作。只需遍历数字即可。
var input = prompt("What number would you like me to give you the factorial of?");
if (input > 0) {
var answer = 1;
var string = input + " =";
for (var i = input; i >= 1; i--) {
answer *= i;
string += " " + i
if (i != 1) {
string += " x"
}
}
console.log(string)
console.log("The factorial of " + input + " is " + answer)
} else {console.log("Invalid input! Program stopped.")}
Java(假设输入在变量input
中):
if (input > 0) {
int answer = 1;
String stringAnswer = input + " =";
for (int i = input; i >= 1; i--) {
answer *= i;
stringAnswer += " " + i
if (i != 1) {
stringAnswer += " x"
}
}
System.out.println(stringAnswer)
System.out.println("The factorial of " + input + " is " + answer)
} else {System.out.println("Invalid input! Program stopped.")}
您可以检查数字是否小于0,否则计算阶乘
let x = prompt('Please enter a positive integer');
if (x < 0) {
console.log('invalid Input! Programmed Stop')
} else {
let val = 1;
for (let k = 1; k <= x; k++) {
val *= k
}
console.log(val)
}