繁体   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