作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如何跟踪用户输入并选出最大和最小的?我也不被允许在代码中放置数组,所以我需要 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.max
和 Math.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/
我是一名优秀的程序员,十分优秀!