2012-08-12 210 views
1

我被模擬考試紙貼在這個問題上。我需要將一個'從'數字乘以一個'n'數字。換句話說:從*(from + 1)(from + 2) ... * n。Java - 使用while循環來解決計算

我需要通過使用while循環來解決這個問題。到目前爲止,我已經做到了這一點,但不知道該怎麼做。

class Fact { 

    private int factPartND(final int from, final int n) { 

     int c = 1; 
     int z = from; 
     int y = n; 
     int num = 0; 

     while (y >= z) { 

      num += from * (from + c);// need to stop multiplying from for each 
            // iteration? 
      c++; 
      y--; 
     } 

     return num; 
    } 

    public static void main(String[] args) { 
     Fact f = new Fact(); 
     int test = f.factPartND(5, 11); 
     System.out.println(test); 
    } 

} 
+0

所以你的輸出應該是理想的5 * 6 * 7 * ... * 11? – 2012-08-12 18:13:00

+0

是的,這是目標 – nsc010 2012-08-12 18:14:28

回答

3

你的計算是:

from * (from + 1) * (from + 2) * ... * (from + n) 

想想每個因素作爲你的循環的一個迭代。

所以,你的第二次迭代應該是(from + i),其中from < i < n通過(from + 1)您的累計值,後來另一次迭代相乘,依此類推,直到您(from + n)乘以你的累加值。

您的代碼非常接近 - 您在每次迭代中都有(from + c),但是您的算術是錯誤的。

正如已經提到,這是一個有點混亂使用cy,讓您的循環軌道,當它足夠的只是測試c

-2
public class Fact { 

    private int factPartND(final int from, final int n) { 
     int m = 1; 
     int result = from; 

     while (m <= n) { 
      result *= (from + m++); 
     } 

     return result; 
    } 

    public static void main(String[] args) { 
     Fact f = new Fact(); 
     int test = f.factPartND(5, 8); 
     System.out.println(test); 
    } 
} 

如果你用5,11來做,你有溢出。那麼你應該使用BigInteger而不是int。

+0

這不是作業,一個MOD先前要求我添加'家庭作業'標籤,即使它是從過去的紙張修訂 – nsc010 2012-08-12 18:28:48

-3

也許是這樣的:

package homework; 
public class Homework { 

    public static int fact(int from, int to){ 
    int result = 1; 
    while(to>0){ 
     result*=from+to; 
     to--; 
    } 
    return result*from; 
    } 
    public static void main(String[] args) { 
    System.out.println(fact(2,4)); 
    } 
} 
+0

這不是家庭作業,一個MOD先前要求我添加'家庭作業「標籤,即使它是從過去的論文修訂 – nsc010 2012-08-12 18:29:16

4

沒有您while循環條件問題。

while(y>=z) 
{ 
    .... 
} 

將執行你的代碼n + 1次。 即如果你想從5執行到11,這種情況將使while循環執行,直到12

更好地利用while(y>z)條件。