Write a class named Averager containing: An instance variable named sum of type
ID: 3614143 • Letter: W
Question
Write a class named Averager containing:An instance variable named sum of type integer, initializedto 0.
An instance variable named count of type integer, initializedto 0.
A method named getSum that returns the value of sum.
A method named add that accepts an integer parameter. Thevalue of sum is increased by the value of the parameter andthe value of count is incremented by one.
A method named getCount that accepts no parameters. getCount returns the value of the count instance variable,that is, the number of values added to sum .
A method named getAverage that accepts no parameters. getAverage returns the average of the values added to sum .The value returned should be a value of type double (and thereforeyou must cast the instance variables to double prior to performingthe division).
what i have so far is
class Averager {
int sum=0;
int count=0;
public int getSum(){ return sum;}
public void add(int n1){sum=sum+n1; count++;}
public int getCount(){ return count;}
public double getAverage(){ return(*sum)/2;}
}
my problem is that i dont know how to write the method forgetAverage
Explanation / Answer
Well, I'm sure you already know how to calculate the average of aset of elements, but to do this in your program you'll need toemploy the power of casting: public double getAverage() { return ((double)getSum() /(double)getCount()); } If you were to divide an integer by an integer then all of yourdecimal values would be truncated. Hope this helps.
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.