Total members 11889 |It is currently Fri Mar 29, 2024 12:50 pm Login / Join Codemiles

Java

C/C++

PHP

C#

HTML

CSS

ASP

Javascript

JQuery

AJAX

XSD

Python

Matlab

R Scripts

Weka





Calculate the average of arrays values:
In the method below trying to calculate average age in each category('o','u','n'). Ages are stored in a separate class.

Code:

public double averageAge
() // calculating average age in each BMI group
    {   
        double numbers
[]=new double[this.list.length];
        double result=0;
        char[] cat={'O','U','N'};
        for (int i=0;i<this.list.length;i++){
            int b=this.list[i].age;
            for(int j=0;j<3;j++){//loop runs three times, as there are three categories
                if(b==cat[0]){
            result=result+b;
            numbers[j]++;}
        }
}
       for (int j=0;j<3;j++) 
        System
.out.println("Average age in group "+cat[j]+ " is "+result/this.list.length);
        return result;
}
 

Result returns 0.. Any ideas how this can be fixed?




Author:
Newbie
User avatar Posts: 1
Have thanks: 0 time

hey brother ,

in line
Code:

          
if(b==cat[0]){
            
result=result+b;
            
numbers[j]++;}
        }
 


this is wrong !. car is array of char , in condition b is (Integer) , so you are comparing the ASCII code of 'o' and the value of integer b . it seems you don't enter this condition ,
i think you should has three counter. one for each group and also a sum for each group . and add conditions in for loop for handling the three cases .

and after all , you calculate the average = sum/counter.

_________________
M. S. Rakha, Ph.D.
Queen's University
Canada


Author:
Mastermind
User avatar Posts: 2715
Have thanks: 74 time

For this message the author DrRakha has received gratitude : deto4ka
Post new topic Reply to topic  [ 2 posts ] 

  Related Posts  to : Average of an array. Please help
 C++ Average example     -  
 Average SQL command     -  
 Array difference for associate array     -  
 compare an array with another array?     -  
 XML Document into an Array in php     -  
 Array sort     -  
 Array C++ Class     -  
 Pop the element off the end of array     -  
 Here is how to display any 2d array     -  
 PHP Array Functions     -  









Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
All copyrights reserved to codemiles.com 2007-2011
mileX v1.0 designed by codemiles team
Codemiles.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com