在理解FOR和WHILE循环时苦苦挣扎

时间:2014-10-06 18:57:09

标签: java loops for-loop while-loop computer-science

描述:编写一个程序,询问用户的起始值和结束值。然后程序应该打印这些值之间的所有值。另外,打印出这两个值之间数字的总和和平均值。

我需要帮助尝试布局程序并使其正常运行。程序运行,期望的结果就不一样了。有人可以帮助我理解我应该做些什么来使它正常工作。谢谢。

但是,这是我的代码:

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

1 个答案:

答案 0 :(得分: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);