2015-10-26 73 views
-1

我想寫一個程序,接受來自用戶的整數,然後它應該計算這個系列S = 1/2! - 三分之一! + 1/4! - 1/5! + ....一路1/x!其中X是從用戶所拍攝的整數,我已經寫了這個代碼來計算的階乘X計算一個系列

import java.util.Scanner; 
public class Factorial { 

    public static void main(String args[]){ 

     Scanner x = new Scanner(System.in); 
     System.out.println("Enter a number: "); 
     int number = x.nextInt(); 
     int fact = 1; 


     for (int i = 1; i <= number; i++){ 
      fact = fact*i; 

     } 

     System.out.println("The factorial of "+number+" is "+fact); 
     x.close(); 
    } 

} 

,但仍然不知道如何在系列代號,任何提示將是真正讚賞。

而且我很抱歉,如果我的代碼是沒有組織,我不知道如何使用計算器工具;(

+1

你在正確的軌道上。一步就是創建一個名爲factorial的函數,它將一個整數作爲參數。然後創建另一個函數,系列,它也需要一個int參數。你需要一個循環,它叫做階乘。一旦你編碼系列和階乘,我們可以幫助你,特別是如果你告訴我們你的期望和你所得到的。 – rajah9

+2

注意'int'不能超過12! – aioobe

回答

2

理想情況下,你想要的是將你的代碼分成多個函數,並進行邏輯思考。

既然你說過你不需要提示,我會盡量讓你走上正確的軌道。


提示1:

獨立代碼爲多個功能

如。

public static int factorial(int n){ 
    int fact = 1; 

    for (int i = 1; i <= n; i++){ 
     fact = fact*i; 

    } 
    return fact; 
} 

這使您可以將代碼拆分爲可管理的塊。在適當的時間調用每個塊。這使你的代碼更易於閱讀和更具重用性


提示2:

一個主要類和其他類功能。

理想情況下,您希望創建兩個類,一個從用戶處獲取輸入,另一個包含您需要的所有功能。主類以輸入將創建其他類的對象

public class Factorial{ 
    public static void main(String args[]){ 

    Scanner x = new Scanner(System.in); 
    System.out.println("Enter a number: "); 
    int number = x.nextInt(); 
    Series s=new Series(number); 
    s.print(); 
    x.close(); 
} 

而且在Series.java

public class Series{ 
    int output; 
    int input; 

    Series(int i){ 
     input=i; 
     //..here you calculate output 
    } 
    public int factorial(int n){ 
     //.... the code 
    } 

    public void print(){ 
    System.out.println("The calculation of " + input + " is " + output); 
    } 


} 

提示3:

使一個很好的簡單的函數來計算輸出。總結所有的階乘隨着時間的推移

for (int i = 2; i <= input; i++) { 
     //if its even 
     if(i%2==0) 
      output = output + 1.0/factorial(i); 
     else 
      output = output - 1.0/factorial(i); 
} 

以下內容添加到您的構造函數,你就會有一個精心打造的Java程序


提示4::這些款項都將是小數,不是整數,所以你需要用double來代替你所有的int s

0

首先,你必須計算條款的和標準模式是像

double sum = 0; 
for (int i = first; i <= last; i++) { 
    sum += term(i); 
} 

然後此話該

  1. 的第一項是項(2)= +1/2!
  2. 第二項是term(3)= -1/3! = -term(2)/ 3
  3. 第三項是+1/4! = -term(3)/ 4

所以你會發現,每個術語可以從以前的一個而容易地獲得。

這導致

double sum = 0; 
double term = (some value); 
for (int i = first; i <= last; i++) { 
    term = (some expression involving i and previous term); 
    sum += term; 
} 

練習留給,呵呵,鍛鍊?