Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Hi my code should do this instruction below but am not getting it at all

The user can enter as many positive floating-point numbers on the console as desired. Zero (or a negative numbers) signals end of input (no more numbers can be entered). After input the program displays ? the smallest number entered (min) ? the largest number entered (max) ? the mean of all numbers entered (mean) Do NOT use arrays for this assignment, even if you know them.

Sample should look like this

enter numbers: 1 2 3 4 5 6 0 numbers entered: 6 minimum: 1.00 maximum:6.00 mean: 3.50

enter numbers: 0 no number entered.

public class LoopStatistics {

public static void main(String[] args) {

    double max, min, sum=0, input, mean=0;
    int counter = 0;

    TextIO.putln("enter numbers:");

    do
    {
        input = TextIO.getDouble();

        min = input;
        max = input;

        counter++;

        if (input > max)
            max = input;

        if ( input < min)
            min = input;

        sum = sum + input;



        } while( input != 0);
    mean = sum / counter;
    TextIO.putf("numbers entered:%d
", counter);
    TextIO.putf("minimum:%f
", min);
    TextIO.putf("maximum:%f
", max);
    TextIO.putf("mean:%f", mean);





}

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
127 views
Welcome To Ask or Share your Answers For Others

1 Answer

You assign your max and min before you test whether they are greater/less than the current max/min:

min = input;
max = input;

This means that they both equal whatever the person entered last.

Tidying up your code and removing those calls yields:

public static void main(String[] args) throws Exception {
    final Scanner scanner = new Scanner(System.in);
    double max = 0;
    double min = Double.POSITIVE_INFINITY;
    double sum = 0;
    int counter = 0;
    while (true) {
        final double d = scanner.nextDouble();
        if (d <= 0) {
            break;
        }
        sum += d;
        max = Math.max(max, d);
        min = Math.min(min, d);
        ++counter;
    }
    System.out.println("Max=" + max);
    System.out.println("Min=" + min);
    System.out.println("Ave=" + sum / counter);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...