如何在while循环中从平均计算中排除负数



我有一个接受用户输入并计算Max, Min和Average的程序。当用户输入任何负数时,程序关闭。如何从平均值计算中排除负数?以下是我目前所掌握的信息。

    // variable
    double n = 1;
    double ave = 0;
    double sum = 0;
    double max = Double.MIN_VALUE; 
    double min = Double.MAX_VALUE ;
    int count = 0;
    double neg;
//creat scanner object
 Scanner input = new Scanner(System.in);

//loop
while (n > 0) { 
System.out.print("Input an income (any negative number to quit): "); 
n = input.nextDouble();
sum = sum + n;
count++;
ave = sum / count;
if(n<0) neg = n;
if(n>max && n >= 0 ) max = n;
if(n<min && n >= 0) min = n;
if(n>0) ave = n; }

   System.out.print(" Average " + ave + "n Maximum " + max + "n Minimum " + min);
}

}

添加if条件:

n = input.nextDouble();
if(n < 0)
    break;
sum = sum + n;

以下代码仅在n不为负时对输入数字求和。

import java.util.Scanner;
public class sample {
    public static void main(String[] args) {
        double n = 1;
        double ave = 0;
        double sum = 0;
        double max = Double.MIN_VALUE;
        double min = Double.MAX_VALUE;
        int count = 0;
        double neg;
        Scanner input = new Scanner(System.in);
        // loop
        while (n > 0) {
            System.out.print("Input an income (any negative number to quit): ");
            n = input.nextDouble();
            if(n >= 0){
              sum = sum + n;
              count++;
            }
            if (n < 0)
                neg = n;
            if (n > max && n >= 0)
                max = n;
            if (n < min && n >= 0)
                min = n;
            if (n > 0)
                ave = n;
        }
        System.out.print(" Average " + ave + "n Maximum " + max
                + "n Minimum " + min);
    }
}

试试这个:

double n = 1;
double ave = 0;
double sum = 0;
double max = Double.MIN_VALUE; 
double min = Double.MAX_VALUE ;
int count = 0;
// create scanner object
Scanner input = new Scanner(System.in);
// loop until n is negative
while (n >= 0) { 
    System.out.print("Input an income (any negative number to quit): "); 
    n = input.nextDouble();
    if (n >= 0) {
        if (n > max) max = n;
        if (n < min) min = n;
        sum = sum + n;
        count++;
    }
}
if (count > 0)
    ave = sum / (double) count;
System.out.print(" Average " + ave + "n Maximum " + max + "n Minimum " + min);

相关内容

  • 没有找到相关文章

最新更新