Java黑皮书课后题第5章:*5.1(统计正数和负数的个数然后计算这些数的平均值)编写程序,读入未指定个数的整数,判断读入的正数有多少个、负数有多少个,然后计算输入值的总和和平均值(不记0,浮点表示)
生活随笔
收集整理的這篇文章主要介紹了
Java黑皮书课后题第5章:*5.1(统计正数和负数的个数然后计算这些数的平均值)编写程序,读入未指定个数的整数,判断读入的正数有多少个、负数有多少个,然后计算输入值的总和和平均值(不记0,浮点表示)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
*5.1(統計正數和負數的個數然后計算這些數的平均值)編寫程序,讀入未指定個數的整數,判斷讀入的正數有多少個、負數有多少個,然后計算輸入值的總和和平均值(不記0,平均值使用浮點表示)
- 題目
- 題目概述
- 運行示例
- 破題
- 代碼
題目
題目概述
*5.1(統計正數和負數的個數然后計算這些數的平均值)編寫程序,讀入未指定個數的整數,判斷讀入的正數有多少個、負數有多少個,然后計算輸入值的總和和平均值(不記0,平均值使用浮點表示)
運行示例
Enter an integer, the input ends if it is 0: 1 2 -1 3 0
The number of positives is 3
The number of negatives is 1
The total is 5.0
The average is 1.25
Enter an integer, the input ends if it is 0: 0
No numbers are entered except 0
破題
代碼
import java.util.Scanner;public class Test5_1 {public static void main(String[] args) {// 接收輸入Scanner input = new Scanner(System.in);System.out.println("Enter an integer, the input ends if it is 0: ");int i = 0, sum = 0, positive = 0, negative = 0; // 計數、總和、正數個數、負數個數int user = 0;boolean bool = true; // 打標while(bool){user = input.nextInt(); // 接收輸入if(user != 0){ // 這個分支主要對非0的輸入進行處理sum += user; // 加總++i; // 計數(總數)if(user > 0){++positive;} // 計數(正數)else{++negative;} // 計數(負數)}else{ // 這個分支對輸入的0進行處理if(i == 0){ // 如果只輸入了一個0的處理:輸出錯誤信息并退出System.out.println("No numbers are entered except 0");System.exit(1);}else{ // 如果已經輸入了多個數字則結束整個循環bool = false;}}}// 計算平均數并輸出結果System.out.println("The number of positives is " + positive);System.out.println("The number of negatives is " + negative);System.out.println("The total is " + sum);System.out.println("The average is " + (sum / i));} }總結
以上是生活随笔為你收集整理的Java黑皮书课后题第5章:*5.1(统计正数和负数的个数然后计算这些数的平均值)编写程序,读入未指定个数的整数,判断读入的正数有多少个、负数有多少个,然后计算输入值的总和和平均值(不记0,浮点表示)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java黑皮书课后题第4章:*4.26(
- 下一篇: Java黑皮书课后题第5章:5.2(重复