我必须编写一个程序,要求用户输入一个整数值。在每个值之后,如果用户想要继续该程序,则用户必须以“y”或“n”作出响应,并且用户输入的每个数字被表示为奇数或偶数。
到目前为止,我已经使用do-while循环完成了这项工作,但我对如何获取用户输入的值的平均值感到困惑。您如何获得所有输入数字的平均值?
到目前为止,这是我的代码:
import java.util.Scanner;
class ProgramTest {
public static void main(String[] args) {
String answer = "";
do {
int num, count = 0;
Scanner scan = new Scanner(System. in );
System.out.print("Enter any number : ");
num = scan.nextInt();
if ((num % 2) == 0) System.out.println(num + " is an even number.");
else System.out.println(num + " is an odd number");
System.out.println("do you want to continue?");
answer = scan.next();
count++;
} while (answer.equals("y"));
}
}
答案 0 :(得分:2)
从问题看起来需要处理以下事项,
- 没有添加添加机制到单个变量。
- 将所有变量放入do ... while循环体......
- 根据要求创建了附加变量。
醇>
使用以下代码段查看我所涵盖的所有内容。
同样做点什么,
String answer = "";
double sum = 0; // use for storing addition to all entered values..
int num, count = 0;
Scanner scan = new Scanner(System.in);
do {
System.out.print("Enter any number : ");
num = scan.nextInt(); // getting input from user through console
sum = sum + num; // add every input number into sum-variable
if ((num % 2) == 0) System.out.println(num + " is an even number.");
else System.out.println(num + " is an odd number");
System.out.println("do you want to continue?");
answer = scan.next(); // ask for still want to repeat..
count++;
} while (answer.equals("y"));
System.out.println("Average is : " + sum + "/" + count + " = "+ (sum /count));
答案 1 :(得分:0)
为了计算平均值,您需要两件事:所有数字的总和和平均值计算中涉及的所有数字的计数。
参与平均值计算的orders.orderitem_set.all
和sum
需要超出count
范围才能在计算中已知阶段。
我也冒昧地修改你的代码
do..while
答案 2 :(得分:-2)
更改您的代码:
import java.util.Scanner;
class ProgramTest {
public static void main(String[] args) {
String answer = "";
int avr =0;
int num, count = 0;
do {
Scanner scan = new Scanner(System. in );
System.out.print("Enter any number : ");
num = scan.nextInt();
if ((num % 2) == 0) System.out.println(num + " is an even number.");
else System.out.println(num + " is an odd number");
System.out.println("do you want to continue?");
avr += num;
answer = scan.next();
count++;
} while (answer.equals("y"));
avr = avr /count;
System.out.println("The avreage of value is:" + avr );
}
}
avr是平均值。这意味着当你输入一个整数。我们添加num和avr。并完成循环。我们分数。像这样:
1-5-9-11
avr = 1 + 5 + 9 + 11;
count = 4;
avr = avr / 4;