2016-03-01 109 views
1

編寫一個要求整數的類num確保它大於0(數據驗證),並計算並返回以下總和系列號碼:while循環,似乎無法讓它得到正確的數據

1/num + 2/num-1 + 3/num-2 + …. (num-1)/2 + num/1 

不要陷入整數除法!

通過調用num = 2;來測試您的方法,您會預期結果爲2.5

public class LengthSeries 
{ 
    public static void main (String[] args) 
    { 
    //variable declarations 
    Scanner keyboard = new Scanner(System.in); 
    int num; 
    int sum = 0; // sum 
    int ctr = 1 ; //counter 

    //Accept the required data 

    System.out.print ("Enter a whole number greater than 0 : "); 
    num = keyboard.nextInt(); 



    //Process the data in order to determine data 
    while (num <= 0){ 
        System.out.println ("Sorry number invalid"); 
        System.out.println ("please write a whole number greater than 0 : "); 
        num = keyboard.nextInt(); 
        } 


    while (num <= 0){ 

        sum += (ctr/num); 
        num -= ctr; 
        ctr++; 
       } 





    //Display the output 
    System.out.println(); 
    System.out.println ("Your sum is: "   +sum); 
    System.out.println ("\n\nWritten by: KinnahRose Lopez"); 

    } //end main method 
} //end LengthSeries class 
+0

'sum'是'int',它永遠不會是2.5。你需要使用'double'。 – Guy

回答

-1
double sum =0; 
for(double i=1.0; i<= num; i+=1.0) { 
    sum+=i/(num-i-1); 
} 
0

你可以試試這個:

public static void main(String[] args) throws Exception { 
    Scanner keyboard = new Scanner(System.in); 
    System.out.print ("Enter a whole number greater than 0 : "); 
    int num = keyboard.nextInt(); 
    while (num<1) { 
     System.out.print ("Enter a whole number greater than 0 : "); 
     num = keyboard.nextInt(); 
    } 

    double sum = 0; 
    double d = num; // convert num to double to get the correct result. 
    for (int i = 1; i <= num; i++) { 
     sum += i/(d-(i-1)); 
    } 
    System.out.println("sum = " + String.format("%.2f", sum)); 
} 

例子:

Enter a whole number greater than 0 : 2 
sum = 2.50 
+0

我還沒有學習,所以我不能使用它。是否有另一種嚴格使用while循環的方法? – KinnahRose

+0

我已經發布完美的作品。您可以複製並粘貼並運行程序,您將看到結果。 –

0
import java.util.Scanner;`enter code here` 
public class Test 
{ 
    public static void main (String[] args) 
    { 
     //variable declarations 
     Scanner keyboard = new Scanner(System.in); 
     int num; 
     double sum = 0; // sum 
     //Accept the required data 
     System.out.print ("Enter a whole number greater than 0 : "); 
     num = keyboard.nextInt(); 
     //Process the data in order to determine data 
     while (num <= 0){ 
      System.out.println ("Sorry number invalid"); 
      System.out.println ("please write a whole number greater than 0 : "); 
      num = keyboard.nextInt(); 
     } 
     int temp = num; 
     for (double i = 1; i <= num; i++) 
     { 
      sum = sum + (i/temp); 
      temp--; 
     } 
     //Display the output 
     System.out.println(); 
     System.out.println ("Your sum is: "   +sum); 
     System.out.println ("\n\nWritten by: KinnahRose Lopez"); 

    } //end main method 
} //end LengthSeries class