簡體   English   中英

如何正確計算數組輸入的平均值?

[英]How to calculate average of array input correctly?

當我輸入任何數量的數字時,它給了我錯誤的平均值我不知道為什么我嘗試了很多方法但平均值仍然不能正常工作我做錯了什么得到錯誤的結果? 任何建議..

import java.util.Scanner;
public class Assignment_Help2 {
    public static void main(String[] args){
        Scanner keyboard = new Scanner (System.in);

        String[] department = new String[5];
        int[] employeesno = new int[5];
        String [] address = new String[5];

        int index;
        index = 0;
        int totalentered = 0;
        String temp;

        // One loop to enter all information
        //INPUT LOOP
        for (index = 0; index < 5; index++)
        {
                System.out.print("Enter a department  or stop ..: ");
                department[index] = keyboard.nextLine();
                if (department[index].equals("stop"))
                {
                    break;

                }
                System.out.print("employees_no: ");
                temp = keyboard.nextLine();
                // convert string to a number & then store it as integer in the array
                employeesno[index] = Integer.valueOf(temp);

                System.out.print("Enter address: ");
                address[index] = keyboard.nextLine();   
                totalentered++;

        } //END OF FOR LOOP

        System.out.println("==================================");   

        System.out.println(String.format("%-20s", "department")+
                String.format("%-18s", "no_employees")+ 
                String.format("%-20s", "Address"));



        // Another separate loop to display the information stored in arrays
        //OUTPUT LOOP   
        for (index = 0; index < totalentered; index++)
        {

            System.out.println(String.format("%-20s", department[index]) + 
                     String.format("%-18d", employeesno[index])+ 
                     String.format("%-20s", address[index]));    

        } 

        int sum1=0;
        double average;
        for(int l=0; l <employeesno.length  ; l++) 
         {
           sum1 += employeesno[l];
         } average= sum1/employeesno.length;
         System.out.println("aver= "+average);
         keyboard.close();      
    }
}

sum1是一個int employeesno.length是一個int ,所以sum1 / employeesno.length由 integer 除法計算。

average = ((double) sum1) / employeesno.length`;

而是在double s 中進行除法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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