【发布时间】:2014-12-01 02:34:50
【问题描述】:
描述:编写一个程序,询问用户一个起始值和一个结束值。然后程序应该打印这些值之间的所有值。此外,打印出这两个值之间的数字的总和和平均值。
我需要帮助来尝试布局程序并使其正确运行。程序运行,想要的结果就是不一样。有人可以帮助我了解我应该怎么做才能使其正常工作。谢谢。
但是,这是我的代码:
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
【问题讨论】:
-
如果你指定你得到什么会有所帮助。为什么要在 while 循环中打印总和?只需添加到循环内的总和并在其下方打印结果。与平均值相同。另外,你为什么要假设你平均得到 4 个值?
-
@HunterLanders 如果我的回答有助于回答您的问题,您介意将我的回答标记为正确吗?
标签: java loops for-loop while-loop computer-science