gpt4 book ai didi

java 。尝试仅计算正数的平均值,如果未输入正数也会显示一条消息

转载 作者:行者123 更新时间:2023-12-02 08:54:12 25 4
gpt4 key购买 nike

我正在尝试做一个练习,但无法弄清楚如何仅计算正数的平均值以及如何在未输入正数的情况下显示特定消息。我希望仅在未输入正数时才显示该消息。谢谢

import java.util.Scanner;

public class AverageOfPositiveNumbers {

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

int entries = 0;
Double average = 0.0;
Double sum = 0.0;


while (true) {
int number = Integer.valueOf(scanner.nextLine());
if (number == 0) {
System.out.println(average);
break;
}
if (number > 0) {

entries = entries + 1;
average = sum / entries;
sum = sum + number;
}
if (number < 0) {
System.out.println("Cannot calculate the average.");
}

}

}
}

最佳答案

您只需要两个变量即可确定平均值。元素的数量(count)以及正值的总和。获取元素后计算平均值。比如,

Scanner scanner = new Scanner(System.in);
int count = 0;
int sum = 0;
while (true) {
int number = Integer.parseInt(scanner.nextLine());
if (number == 0) {
break;
} else if (number > 0) {
count++;
sum += number;
}
}
if (count > 0) {
System.out.printf("The average is %.2f%n", sum / (double) count);
} else {
System.out.println("Cannot calculate the average.");
}

关于 java 。尝试仅计算正数的平均值,如果未输入正数也会显示一条消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60591899/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com