簡體   English   中英

Java中的數組加法?

[英]Array Addition in java?

到目前為止,我有一個程序要求用戶選擇一些元素。 然后,程序要求用戶選擇元素數量所指示的次數。 我將如何僅使用數組以及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);
    }
    }

您的程序可能像:

//編寫一個可以找到一組數字的方差的應用

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 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM