Monday, May 24, 2010

What is wrong with this C++ program?

#include%26lt;iostream%26gt;


using namespace std;





int main()


{


int numCount, total;


double average;





cout %26lt;%26lt; "How many numbers do you want to average? ";


cin %26gt;%26gt; numCount;


for (int count = 0; count %26lt; numCount; count++)


{


int num;


cout %26lt;%26lt; "Enter a number: ";


cin %26gt;%26gt; num;


total += num;


}


average = total / numCount;


cout %26lt;%26lt; "The average is " %26lt;%26lt; average %26lt;%26lt; endl;


return 0;


}

What is wrong with this C++ program?
dude int total get initialized to garbage value..


so use


int numCount,total=0;


this should giv u the correct answer





#include%26lt;iostream%26gt;


using namespace std;





int main()


{


int numCount, total=0;


double average;





cout %26lt;%26lt; "How many numbers do you want to average? ";


cin %26gt;%26gt; numCount;


for (int count = 0; count %26lt; numCount; count++)


{


int num;


cout %26lt;%26lt; "Enter a number: ";


cin %26gt;%26gt; num;


total += num;


}


average = total / numCount;


cout %26lt;%26lt; "The average is " %26lt;%26lt; average %26lt;%26lt; endl;


return 0;


}
Reply:total/numCount is integer devided by integer wil result in fraction part truncated. Also all vaiables need to be initialized to 0.





Two Solutions


1. Use datatype casting: i.e., You can replace


average = total/numCount ;


with


average=(double)total / (double) numcount;





2. Initialize numcount and Total as double/float datatype


instead of integer.
Reply:It looks ok to me. The only thing I would suggest is initializing your variables to something so you know you don't have junk in them. So set numCount and total to 0 at the top and also set average to 0.0 and don't forget to set num = 0 in your for loop as well. I'm not sure exactly what the problem is or if there is one since you didn't mention a specific error.
Reply:Try placing the "int num;" outside of the for.





for total, make it "total = total + num;"





Remember to close everything, even "for" with a ";"





If this doesn't fix it, can you say what exactly the problem is when it runs?





It's been a long time since C++, sorry if I'm wrong.

augustifolia

No comments:

Post a Comment