0

到目前为止,我有一个程序要求用户选择一些元素。然后程序要求用户选择元素数量所指示的次数。我如何仅使用数组以及 while 或 for 循环来找到这组数字的方差。没有什么太花哨的,因为我在高中。以下是我当前的代码:

//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);
    }
    }
4

1 回答 1

0

你的程序可能是这样的:

//编写一个应用程序来查找一组数字的方差

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);
    }
}
于 2013-10-11T20:22:47.067 回答