2014-10-06 70 views
1

描述:編寫一個程序,要求用戶輸入起始值和結束值。程序應該在這些值之間打印所有值。另外,打印這兩個值之間的數字的總和和平均值。努力瞭解FOR和WHILE循環

我需要幫助,試圖佈置程序並使其正常運行。程序運行時,所需的結果不盡相同。有人可以幫助我瞭解我應該怎樣做才能正常工作。謝謝。

但是,這裏是我的代碼:

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 

public class Prog152d 
{ 
    public static void main(String[] args) throws IOException 
    { 
     BufferedReader userin = new BufferedReader(new InputStreamReader(System.in)); 
     String inputData; 
     int starting, ending, sum; 
     double avg; 
     sum = 0; 
     System.out.print("Enter Starting Value: "); 
     inputData = userin.readLine(); 
     starting = Integer.parseInt(inputData); 
     System.out.print("Enter Ending Value: "); 
     inputData = userin.readLine(); 
     ending = Integer.parseInt(inputData); 
     while (starting <= ending) 
     { 

      System.out.println(starting); 
      sum = sum + starting; 
      avg = sum/4; 


      System.out.println("Sum of the numbers " + starting + " and " + ending + " is " + sum); 
      System.out.println("The average of the numbers " + starting + " and " + ending  + " is " + avg); 
     starting++; 
     } 
    } 
} 

樣本輸出:

Enter Starting Value: 5 

Enter Ending Value : 8 

5 

6 

7 

8 

Sum of the numbers 5..8 is 26 

The average of the numbers 5..8 is 6.5 
+0

這將有所幫助,如果你指定你取而代之。 你爲什麼要在while循環中打印總和?只需添加循環內的和,並在其下面輸出結果。與平均水平相同。另外,你爲什麼平均得到4個值? – 2014-10-06 19:27:15

+0

@HunterLanders如果我的回答有助於回答你的問題,你會介意將我的回答標爲正確嗎? – bwegs 2015-03-13 13:25:48

回答

0

我看到的第一個問題是以下行:

avg = sum/4; 

不要使用一個恆定的值(在這種情況下是4),除非它是唯一的可能性。相反,使用一個變量,並將其值等於起點和終點之間的差值:

int dif = ending - starting + 1; // add one because we want to include end ending value 
avg = sum/dif; 

另外,平均只需要在最後一次計算,因此你的循環內不屬於。做出這些調整後,你會最終得到類似這樣的東西......

int start = starting; // we don't want to alter the value of 'starting' in our loop 
while (start <= ending) 
{ 
    System.out.println(start); 
    sum = sum + start; 
    start++; 
} 

int dif = ending - starting + 1; 
avg = (double)sum/dif; 
System.out.println("Sum of the numbers between " + starting + " and " + ending + " is " + sum); 
System.out.println("The average of the numbers between " + starting + " and " + ending + " is " + avg);