Вопрос

I have so far a program that asks the user to choose a number of elements. The program then asks the user to choose numbers as many times indicated by the number of elements. How would I find the variance of this set of numbers using only arrays and either while or for loops. Nothing too fancy as I am in high school. Below is my current code:

//write an app that finds the variance of a set of numbers
class temp1 {
    public static void main(String args[])
    {
    int counter = 0;
    String question;
    question = "How many elements do you want?: ";
    EasyReader console = new EasyReader();
    System.out.println(question);
    int answer;
    int answer2;
    answer = console.readInt();
    int[] numbers = new int[answer];
    int mean;
    System.out.println();
    while(true)
    {
    System.out.println("Please enter a number: ");
    answer2 = console.readInt();
    counter++;
    if(counter==answer)
    {
    break;
    }
    }
    mean = (numbers[0]+numbers[1]+numbers[2]+numbers[answer])/answer;
    System.out.print(mean);
    }
    }
Это было полезно?

Решение

Your program may be like:

//write an app that finds the variance of a set of numbers

class temp1
{
    public static void main(String args[])
    {
        int counter = 0;
        String question;
        question = "How many elements do you want?: ";
        EasyReader console = new EasyReader();
        System.out.println(question);
        int answer;
        int answer2;
        answer = console.readInt();
        int[] numbers = new int[answer];
        int mean;
        System.out.println();
        while (true)
        {
            System.out.println("Please enter a number: ");
            answer2 = console.readInt();
            numbers[counter] = answer2;
            counter++;
            if (counter == answer)
            {
                break;
            }
        }
        counter = 0;
        int sum = 0;
        while(true)
        {
            sum = sum + numbers[counter];
            counter++;
            if(counter == answer)
            {
                break;
            }
        }
        mean = sum / answer;
        System.out.print(mean);
    }
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top