请帮我弄清楚我的错误。当我按照升序输入分数(如4,5)时,最小值为100.我不知道如何更改它?
这是我的代码:
float score=0,min=100,max=0,sum1=0,count=0,sum2=0;
float average,sd;
Scanner a=new Scanner(System.in);
while(score>=0)
{
System.out.println("enter the score(a negative score to quit)");
score=a.nextInt();
if(score<0)
break;
if(score>=max){
max=score;
sum1+=max;
}
else
{
min=score;
sum2+=min;
}
count++;
}
average=(sum1+sum2)/(count++ );
System.out.println("the average : " + average);
System.out.println( "the maximum score: "+ max);
System.out.println("the min score: "+ min );
答案 0 :(得分:0)
将您的else
更改为else if (score < min)
,即可获得正确的最低要求。
之所以如此,它检查score
是否大于当前max
,如果不是这样的话,那么由于其他原因它只是假设score
是新的min
。
if (score >= max) {
max = score;
}
else if (score < min){
min = score;
}
// Just add the score value to the sum, it doesn´t matter if it´s min or max
sum2 += score;
count++;
答案 1 :(得分:0)
简化:
while((score = a.nextInt()) >= 0) {
min = Math.min(min, score);
max = Math.max(max, score);
sum += score;
average = sum / count++;
}
答案 2 :(得分:0)
我认为你的问题过于复杂:你应该尝试按逻辑步骤思考手头的任务:
看起来像这样:
import java.util.*;
public class MaxMinAverage {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double score, currentMinimum = Integer.MAX_VALUE, currentMaximum = Integer.MIN_VALUE, count;
while (in.hasNextInt()) {
int nextInt = in.nextInt();
if (nextInt < 0) { //break out of the loop
break;
} else {
score += nextInt;
count++;
if (nextInt > currentMaximum) {
currentMaximum = nextInt;
} else if (nextInt < currentMinimum) {
currentMinimum = nextInt;
}
}
}
System.out.println("Max: " + currentMaximum);
System.out.println("Avg: " + (score / count));
System.out.println("Min: " + currentMinimum);
}
}