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

时间:2016-07-01 04:53:56

标签: java netbeans

我有一个接受用户输入并计算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);

}

}

3 个答案:

答案 0 :(得分:1)

添加if条件:

n = input.nextDouble();

if(n < 0)
    break;

sum = sum + n;

答案 1 :(得分:0)

以下代码仅在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);
    }
}

答案 2 :(得分:0)

试试这个:

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);