2014-10-07 61 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