一系列数字的算术平均值

时间:2014-10-21 15:57:38

标签: java

声明说:

  

从键盘读取连续整数。当你读-1时,   程序必须指出我们读取的1到100之间的数字   什么是他们的算术平均值(MediaNum.java)。

我推这段代码:

import java.util.*;


public class MediaNum {

    public static void main(String[] args) {

        Scanner entrada = new Scanner(System.in);
        double number, sum=0, medium;
        int counter=0;
        System.out.println("When you want to finish enter '-1'.");
        System.out.println("Enter the numbers:");
        number = entrada.nextDouble();
        while (number != -1){
            sum = sum + number;
            counter++;
            number = entrada.nextDouble();
        }
        if (number == -1){
            counter++;
            System.out.println("counter");
        }
        if (number == -1 && number < 101){
            medium = sum/counter;
            System.out.println("The medium of the numbers entered is: "+medium);
        }
    }   
}

介质的一部分和我放-1的部分计数器完成是正确的但是错误是当我把一个数字放在100以上时,计数器会计算这个数字并且介质将是不正确的。

4 个答案:

答案 0 :(得分:1)

如果符合条件,请计算数字:

while (number != -1){
    if(number >= 1 && number <= 100) {
        sum += number;
        counter++;
    }
    number = entrada.nextDouble();
}

答案 1 :(得分:0)

这是问题

  while (number != -1){
            sum = sum + number;
            counter++;
            number = entrada.nextDouble();
        }

您正在添加每个号码,您只需要那些&lt; 100

答案 2 :(得分:0)

试试这段代码

import java.util.*;


public class MediaNum {

    public static void main(String[] args) {

        Scanner entrada = new Scanner(System.in);
        double number=0, sum=0, medium=0;
        int counter=0;
        System.out.println("When you want to finish enter '-1'.");
        while(number!=-1){
            System.out.println("Enter the numbers:");
            number = entrada.nextDouble();
            if((number>100 || number<1)&&number!=-1){
                continue;
            }
            if(number==-1){
                break;
            }
            sum += number;
            counter++;
        }
        System.out.println("counter :" +counter);
        if(counter!=0){
            medium = sum/counter;
        }
        System.out.println("The medium of the numbers entered is: "+medium);
    }
}

答案 3 :(得分:0)

你可以尝试这个。它工作。我使用递归函数。如果它有效,添加注释。

import java.util.*;
class AM{
    double s=0;int co=0;
    double p;
    public void show(){

        Scanner sc=new Scanner(System.in);
        System.out.println("Enter the number:-");
        p=sc.nextDouble();
        if(p!=-1&&p<=100){
            s+=p;
            co++;
            show();
        }
        else
        {
            System.out.println("The average is:-"+(s/co));
            System.out.println(co+" "+"numbers were entered.");

        }
    }
}