gpt4 book ai didi

java - Do While 循环,跟踪用户输入 Java

转载 作者:行者123 更新时间:2023-12-02 01:55:06 26 4
gpt4 key购买 nike

如何跟踪用户输入并选出最大和最小的?我也不被允许在代码中放置数组,所以我需要 if 语句。我尝试过嵌套 if 语句,当用户输入的数字不断变化时,我不知道如何比较它。我已经能够打印一些结果,但通常最终以我输入的最后一个数字作为输出。一些帮助将不胜感激。

    Scanner scan = new Scanner(System.in);

double sum = 0;
int totalnumber = 0;
double avg = 0;
double input;
double num = 0;
double large = 0;
double small = 0;

do{
System.out.println("Please type in a number. Type 0 to quit.");
input = scan.nextDouble();
scan.nextLine();



if(input == 0)
{
break; //breaks the loop when the user enters 0
}
else
{
totalnumber += 1; //tracker for how many times user enters a number
sum+= input; //get the sum of the entered inputs
//large = input;
//small = input;
//num = input;


}
}while(true);


avg = sum / totalnumber; //getting the average of the inputs

if(totalnumber == 0) //if the user only put in 0
{
System.out.println("You didn't type anything in.");
}
else //if the user entered 1 or more numbersk
{
System.out.println("The sum of your inputs is: " + sum);
System.out.println("The total number of inputs you provided was: " + totalnumber);
System.out.println("The average of your inputs is: " + avg);
System.out.println("The highest number you input was: " + large);
//System.out.println("The lowest number you input was: " + small);
}
}

}

最佳答案

您可以使用 Math.maxMath.min 方法。

在此之前,请将值设置为

int large = Math.MIN_VALUE;
int small = Math.MAX_VALUE;
// above do not need to be doubles

{
totalnumber += 1; //tracker for how many times user enters a number
sum+= input; //get the sum of the entered inputs
large = Math.max (large, input);
small = Math.min (small, input);
}

关于java - Do While 循环,跟踪用户输入 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52417813/

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