Sunday, July 12, 2009

C++ Question--Why does this display the femgpa as -int and the malgpa as 0?

#include %26lt;iostream%26gt;


#include %26lt;fstream%26gt;


#include %26lt;cassert%26gt;





using namespace std;





int main()


{


int femcount=0, malcount=0;


double femgpa=0, malgpa=0, malsum, femsum, gpa;


char gender, m, f;





ifstream infile;





infile.open("gpa.txt");


assert(infile);





infile %26gt;%26gt; gender;





while (infile)


{





if (gender == f)


{


femsum = femsum + gpa;


femcount++;





}





else


{


malsum = malsum + gpa;


malcount++;





}


infile %26gt;%26gt; gender %26gt;%26gt; gpa;


}





femgpa = femsum / femcount;


malgpa = malgpa / malcount;





cout %26lt;%26lt; "The average female GPA is " %26lt;%26lt; femgpa %26lt;%26lt; endl;


cout %26lt;%26lt; "The average male GPA is " %26lt;%26lt; malgpa %26lt;%26lt; endl;





return 0;





}

C++ Question--Why does this display the femgpa as -int and the malgpa as 0?
I think there is a typed letter 'f' or 'm' in the text file, yes?





So I think you mean to test variable gender for the letter f or m.





I suggest you:





1. delete variables f and m, like so:


char gender;





2. then test for 'f' (female) in your code like so:


if (gender == 'f' || gender == 'F' ) //allow upper / lower case


{


....

pear

No comments:

Post a Comment