gpt4 book ai didi

java - 需要帮助找到平均值

转载 作者:行者123 更新时间:2023-11-30 03:43:47 27 4
gpt4 key购买 nike

我似乎无法弄清楚如何根据用户输入的分数来计算平均分数。我也无法让它停止排除大于 100 或小于 0 的输入。有人可以告诉我我做错了什么吗?谢谢。

public static void main(String[] args) {


Scanner scan = new Scanner(System.in);

int sum = 0;
int inputNumber;
int numberExams;
float averageScore;
double max = 0;
double min = 101;


System.out.println("Enter the total number of exams you want a average");
numberExams = scan.nextInt();

System.out.println("Please enter " + numberExams + " numbers:");

for(int i = 1; i<=numberExams ;i++){
inputNumber = scan.nextInt();
sum = sum + inputNumber;
System.out.println();

if(inputNumber > max){
max = inputNumber;
}
if(inputNumber < min){
min = inputNumber;
}
if(inputNumber > -1 && inputNumber < 101){
sum = sum + inputNumber;
}
else{
System.out.println("You entered a number that wasn't in the range of 0 to 100");
}
}


averageScore = sum / numberExams;

System.out.println( "The Max Exam Score is: " + max );
System.out.println( "The Minimum Exam Score is: " + min );
System.out.println("The Average Exam Score is: " + averageScore );
}
}

最佳答案

您在 for 循环 中执行了两次 sum = sum + inputNumber 操作。

此外,您需要将 int 转换为 double 来计算平均值:

double average = ((double) sum) / numberExams;

关于java - 需要帮助找到平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26244472/

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