我正在参加一个虚拟的高中班,这不是我认为的那样,我很困惑,至少可以说。我的作业是这样的:java编程阶乘帮助请
练习6.1
在数学中,一个数的一个阶乘表示为写n!并且是n和所有其他数字小于n的乘积。例如,5!是5 * 4 * 3 * 2 * 1。
- 创建一个名为Factorial的新项目。
- 编写一个采用整数作为参数的析因方法,并以 整数形式返回结果。它应该使用循环来计算阶乘。
- 主要提示用户输入一个数字,然后调用阶乘方法。显示返回的结果。
这是我的代码至今:
import java.util.Scanner;
import javax.swing.JOptionPane;
class Factorial
{
public static void main(String[] args) {
String choice = JOptionPane.showInputDialog(null, "Enter a number.");
int numberChoice = Integer.parseInt(choice);
int triple;
triple = factorialNumber(numberChoice);
System.out.println(JOptionPane.showMessageDialog(null, triple, "Output:"));
}
// int num;
//Scanner input = new Scanner(System.in);
//num = input.nextInt();
//int FactInput = factorialNumber(num);
public static double factorialNumber(int){
//declaring variables
//int num;
int fact=1; //placeholder
//using the scanner
// Scanner input = new Scanner(System.in);
//user input
System.out.println("Enter a number: ");
// num = input.nextInt();
//for statement
for (int i=2;i<=num; i++){
//multiple assignment
fact=fact*i;
//print the result
System.out.print("The factorial of your number is ");
return fact;
}
return fact;
}
}
我在哪里何去何从? 所有帮助表示赞赏 - 谢谢!
究竟是什么问题? – Radiodef 2014-10-07 21:39:54
消除对“swing”或“JOptionPane”的所有引用。他们让你感到困惑,而且没有必要,因为这个问题只能通过命令行来解决。 – Stewart 2014-10-07 21:46:28
它看起来像你的代码中的主要问题是你在计算阶乘的循环中返回。另外,除非需要('public static double factorialNumber(int)'应该是'public static int factorialNumber(int)''),否则通常不需要使用浮点数学运算。 – Jason 2014-10-07 21:50:37