亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

計算整數序列的最大值和最小值的程序

計算整數序列的最大值和最小值的程序

開滿天機 2023-03-31 17:07:11
在我的代碼中,我試圖從用戶輸入的數字序列中找到序列的平均值、最大數和最小數。我的問題是我不知道如何編寫代碼,所以當用戶鍵入 0 或負整數時停止并進行計算。public class Sequence2{    public static void main(String[] args)    {        Scanner keyb = new Scanner(System.in);        int count = 0;        double sum = 0;        double avg = 0;        int n;        System.out.println("Enter a sequence of positive integers, which will end with either 0 or a negative integer. ");        int max = keyb.nextInt();        int min = keyb.nextInt();        while (keyb.hasNextInt())        {            n = keyb.nextInt();            if (n > max)            {                max = n;            }            if (n < min)            {                min = n;            }            count++;            sum += n;        }        System.out.println("The maximum value is: " + max);        System.out.println("The minimum value is: " + min);        avg = sum / count;        System.out.println("Average = " + avg);    }}
查看完整描述

4 回答

?
暮色呼如

TA貢獻1853條經驗 獲得超9個贊

解決這個問題的關鍵點是維護在循環外定義的最小值和最大值的狀態。特別是,最小值應該用最大可能的整數值作為種子,而最大值可以用零作為種子。


public static void main(String[] args) {

    int minimum = Integer.MAX_VALUE;

    int maximum = 0;

    int total = 0;

    int counter = 0;

    Scanner keyb = new Scanner(System.in);


    while (true) {

        int num = keyb.nextInt();

        if (num <= 0) {

            System.out.println("Exiting input loop.");

            break;

        }


        if (num < minimum) {

            minimum = num;

        }

        if (num > maximum) {

            maximum = num;

        }

        total += num;

        ++counter;

    }


System.out.println("minimum: " + minimum);

System.out.println("maximum: " + maximum);

System.out.println("average: " + (total / counter));

我省略了一些事情,例如處理用戶沒有在掃描儀中輸入有效整數的可能性。此外,我假設用戶總是會輸入至少一個有效整數。如果不是,我們將不得不在最后處理平均算術以避免被零除。


查看完整回答
反對 回復 2023-03-31
?
慕勒3428872

TA貢獻1848條經驗 獲得超6個贊

做這件事有很多種方法。如果我們想通過對現有代碼進行最少的更改來做到這一點,我會說最簡單的選擇是添加一個布爾標志,指示是否繼續循環:

在你的 while 循環之前

boolean userWantsToQuit = false;

這應該是你的循環條件:

while (keyb.hasNextInt() && !userWantsToQuit)

然后在您的 while 循環中,您需要在其他 if 語句之前添加此 if 語句

if(n<=0){userWantsToQuit=true}

您可能還想將其他 if 語句切換為 else if 語句附加到此條件 - 否則您將始終得到 0 或您用來退出的負數作為輸入的最小數字。

您還可以使用 break 語句而不是布爾標志 - 這是個人喜好問題。出于某種原因,我總是被教導要避免 break 語句,所以我通常使用標志,但兩者都是有效的方法。

這不是最慣用的解決方案,但它是最相似地遵循您已經設置的模式的解決方案。


查看完整回答
反對 回復 2023-03-31
?
飲歌長嘯

TA貢獻1951條經驗 獲得超3個贊

如果你想讓它更像 Java-8,就像一個想法。

  1. 首先,您從用戶那里收集所有整數List<Integer>

  2. 然后計算IntSummaryStatistics并提取最小值、最大值和平均值:

result = list.stream().collect(Collectors.summarizingInt(Integer::intValue));


min = result.getMin();

max = result.getMax();

average = result.getAverage();


查看完整回答
反對 回復 2023-03-31
?
慕姐8265434

TA貢獻1813條經驗 獲得超2個贊

您走在正確的軌道上,但是您不需要avg在代碼頂部預先聲明變量,因為它只是在最后計算的。


對于循環退出條件,當輸入小于或等于零時,使用 if 語句中斷 while 循環:


import java.util.Scanner;


public class Sequence2 {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        int count = 0, overallMax = 0, overallMin = Integer.MAX_VALUE;

        double sum = 0;

        System.out.println("Enter a sequence of positive integers, which will end with either 0 or a negative integer. ");


        while (scanner.hasNext()) {

            if (scanner.hasNextInt()) {

                int num = scanner.nextInt();

                if (num <= 0) {

                    scanner.close();

                    break;

                }

                overallMax = Math.max(overallMax, num);

                overallMin = Math.min(overallMin, num);

                count++;

                sum += num;

            } else {

                System.out.println("ERROR: Invalid Input. Enter a integer!");

                scanner.next();

            }

        }


        System.out.println("The maximum value is: " + overallMax);

        System.out.println("The minimum value is: " + overallMin);

        double avg = sum / count;

        System.out.println("Average: " + avg);

    }

}

用法示例:


Enter a sequence of positive integers, which will end with either 0 or a negative integer.

4

a

ERROR: Invalid Input. Enter a integer!

2

6

-1

The maximum value is: 6

The minimum value is: 2

Average: 4.0


查看完整回答
反對 回復 2023-03-31
  • 4 回答
  • 0 關注
  • 185 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號