努力了解FOR和WHILE循环
问题描述:
描述:编写一个程序,要求用户输入起始值和结束值。程序应该在这些值之间打印所有值。另外,打印这两个值之间的数字的总和和平均值。努力了解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
答
我看到的第一个问题是以下行:
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);
这将有所帮助,如果你指定你取而代之。 你为什么要在while循环中打印总和?只需添加循环内的和,并在其下面输出结果。与平均水平相同。另外,你为什么平均得到4个值? – 2014-10-06 19:27:15
@HunterLanders如果我的回答有助于回答你的问题,你会介意将我的回答标为正确吗? – bwegs 2015-03-13 13:25:48