Sunday, August 2, 2009

Is this C ++ problem right? can someone please check out!?

first of all i don't quite undurstand the problem and i want to know if it was understood right - this is the problem:





The Federal Reserve wants a program that can give the average interest rate on mortgages using data from four nationally ranked banks. Your tasks are to create a program that calculates the average of values stored in a one-dimensional double array named rates. The program should display the average rate on the screen.


Use the following data to:


Bank of America 6.2%, RBC Centura 7.1%, BB%26amp;T 5.9%, Federal Credit Union 6.0%


code:


#include %26lt;iostream%26gt;





using namespace std;





int main()


{


//declare array


double total = 0;


double average = 0;


double rate[4] = {6.2, 7.1, 5.9, 6.0};








// calculate sum


for (int x = 0; x %26lt; 4; x = x + 1)


total = total + rate[x];


//end for





//calculate and display average


average = total / 4;





cout %26lt;%26lt; "Average: " %26lt;%26lt; average %26lt;%26lt;endl;


return 0;


}//end of the displayAverage program

Is this C ++ problem right? can someone please check out!?
That is what the problem is asking you to do.





And I cannot see anything immediately wrong with it.





Only mathematically, you would not put in percent values as that but as 6.2% = 0.062, 7.1% = 0.071 and so on. But in the end your output would be in percent value. You just have to be aware of the difference between percent and the actual number.





Good job.
Reply:Your answer looks fine. Though I would change:


total = total + rate[x];


to


total += rate[x]; // cleaner


and I would limit the hard coded use of 4 to the array declaration.


using instead:


int count = sizeof(rate)/sizeof(double); // more universal


so if you could change the array size and nothing else would change.


No comments:

Post a Comment