2014-10-07 66 views
-2

我正在参加一个虚拟的高中班,这不是我认为的那样,我很困惑,至少可以说。我的作业是这样的: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; 
    } 
} 

我在哪里何去何从? 所有帮助表示赞赏 - 谢谢!

+0

究竟是什么问题? – Radiodef 2014-10-07 21:39:54

+1

消除对“swing”或“JOptionPane”的所有引用。他们让你感到困惑,而且没有必要,因为这个问题只能通过命令行来解决。 – Stewart 2014-10-07 21:46:28

+0

它看起来像你的代码中的主要问题是你在计算阶乘的循环中返回。另外,除非需要('public static double factorialNumber(int)'应该是'public static int factorialNumber(int)''),否则通常不需要使用浮点数学运算。 – Jason 2014-10-07 21:50:37

回答

0
System.out.println("Output: " + triple); 

static int factorialNumber(int num) { 

没有System.out.println在阶乘函数结束。

删除循环内的返回;你会循环一次,然后返回。

并尝试在调试器中使用单步选项。

1

最好使用long而不是int,阶乘增长得很快。 下面是一个简单的函数,使用recursion

private static long factorial(int n) { 
    return (n==1)?1:n*factorial(n-1); 
} 

System.out.println(factorial(20)); // gives 2432902008176640000 
2

好像你必须下来的大部分。你不需要在for循环中返回。您只能在for循环完成后返回阶乘,因为这是计算完成时的阶乘。另外,不要担心在factorialNumber()方法中打印输出。你的方法找到这个值,然后你可以在你的主要方法中打印出来。

1.Get数为阶乘
它2.发送到factorialNumber()方法
3.Run for循环,直到索引达到数
4.Return的值。
5.打印的值

一些其他错误:
-System.out.println(JOptionPane.showMessageDialog(NULL,三重, “输出:”)); - >省略的System.out.println
-public静态双factorialNumber(INT){应该有 “民”, “INT”
-remove的的System.out.println后,你的内for循环

0

阶乘返回任何数字总是迅速增长。所以你需要确保你采取适当的数据类型。你的程序只接受int和Java,整数是32位,范围从-2,147,483,648到2,147,483,647。因此,如果您的因子计算超出了整数限制,那么您的程序可能不会给出预期的结果。请参阅此链接factorial using big integer