Monday, May 24, 2010

Very Basic C++ Question About Float!?

I've just started a C++ class and we have to write a program that asks for 5 grades from the user and then calculates the average. I almost have the whole thing down and it compiles and runs smoothly, but then my teacher reminded us that the answers could turn out to be decimals, of course. I know that float is used for decimals but we haven't done any examples with this type of variable. I'm guessing that I'll just have to do something in this section:





#include%26lt;iostream%26gt;


using namespace std;





int main ()


{


string username;


int grade1;


int grade2;


int grade3;


int grade4;


int grade5;


int avg = 0;


int sum = 0;





Thanks in advance!

Very Basic C++ Question About Float!?
in above programs or hints do a s\mall change that is


avg=float(sum)/5.0;


or


avg=float(grade1+grade2+grade3+grade4+...
Reply:not sure about c++, but try to do this





float avg = 0.0;





sum = grade1 + grade2 + grade3 + grade4 + grade5 ;


avg = sum / 5.0 ;





note the last line is over 5.0 not over 5, since i think over 5 will just round the actual average before assigning it to avg
Reply:Ok. floats are just like ints but can do decimals. So just change your average variable into a float like this:





float avg = 0;





That's it!
Reply:A float is used to store a value corresponding to a single-precision real number ( a decimal number ). Since you are trying to calculate the average, you have to change the line:





int avg = 0;





to





float avg = 0.0;





Then you can calculate the average using:





avg = (grade1 + grade2 + grade3 + grade4 + grade5)/(5.0);





or, if you prefer: avg = sum/(5.0);





I hope this helps you.


No comments:

Post a Comment