gpt4 book ai didi

java - 最小/最大值无故改变

转载 作者:行者123 更新时间:2023-12-01 11:47:44 24 4
gpt4 key购买 nike

这个问题我绞尽脑汁也想不出来。当从用户输入的数字数组中计算出最小值和最大值时,最小值会在第 4 次或第 5 次迭代时更改为不是最小值的数字。我一直试图慢慢地浏览并看看发生了什么,但也许我已经关注这个问题太久了。任何帮助将不胜感激。

 public class average2
{
public static void main (String [] args)
{


double[] scores = new double [25];
double max= 0 ;
double min = 0;
int count = 0;
double sum = 0;
double score= 0;
double average = 0;
int i;


while ((count < 25)&&((score=IO.readDouble("Enter Scores, -1 to Quit")) >0))
{ {scores[count++]=score;}


min= scores[0];
max = scores[0];
for (i=0;i<scores.length; i++)
if (score > max)
{ max = score;
min = min;}
if (score < min)
{ min = score;}


sum = sum + score;
average = sum /scores.length;


System.out.println(score); //this line is for testing purposes only
System.out.println("Max is " + max);
System.out.println("Min is " + min);
System.out.println("The sum of the scores is " + sum);
System.out.println("The average of the scores is " + average);



count = count + 1;

}// end while loop


}// end main

}//end class

最佳答案

请始终记住,如果您不使用 {},则 for 中将仅运行一行代码。因此,良好的编码风格是始终使用 {}!

for (i=0;i<scores.length; i++){
if (score > max) { max = score; min = min;}
if (score < min) { min = score;}
}

关于java - 最小/最大值无故改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29024939/

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