描述
编写程序,输入若干个整数,如果输入0,输入即终止。判定读入的整数中有多少个正整数、多少个负整数,并计算这些整数的总和和平均值(0不计算在内)。平均值结果保留2位小数。
【输入】
一行中给出若干个整数,其间以空格分隔。如果输入0,输入即终止。
【输出】
分行输出这些整数中的正整数个数、负整数个数、总和、平均值(0不计算在内,结果保留2位小数)。
若只输入0,则输出:No input。
【输入示例】
-1 -2 -3 -4 -5 6 7 8 9 0
【输出示例】
4
5
15
1.67
本题是循环结构的练习题,可以通过两种办法来解决,分别是使用while循环和do while循环的解法。
①
import java.util.Scanner;public class test {public static void main(String[] args) {Scanner in = new Scanner(System.in);int countPositive = 0;int countNegative = 0;int count = 0;int value, sum = 0;while (true) {value = in.nextInt();if (value > 0) {countPositive++;} else if (value < 0) {countNegative++;} else if (value == 0) {break;}sum += value;}count = countNegative + countPositive;// 输出结果if (count == 0)System.out.println("No input");else {System.out.println(countPositive);System.out.println(countNegative);System.out.println(sum);System.out.printf("%.2f\n", (sum * 1.0 / count));}in.close();}}
以上是使用while循环的解题方法👆
②
import java.util.Scanner;public class test {public static void main(String[] args) {Scanner in = new Scanner(System.in);int countPositive = 0;int countNegative = 0;int count = 0;int value, sum = 0;do {value = in.nextInt();if (value > 0)countPositive++;else if (value < 0)countNegative++;sum += value;}while(value != 0);count = countPositive + countNegative;// 输出结果if (count == 0)System.out.println("No input");else {System.out.println(countPositive);System.out.println(countNegative);System.out.println(sum);System.out.printf("%.2f\n", (sum * 1.0 / count));}in.close();}}
以上是用do while循环的解题方法👆