Thursday, July 30, 2009

Easy Basic C++ Programming Help?

1) My odd counter won't work when I try to count the odd scores when I enter 39, 43, 62.


2) I'm trying to repeat the program when i press any letter except 'x'. when i do that, i get the same results as the first time around.





{





int counter = 0;


int oddcount = 0;


int num1;


int scores;


char letter;


int highestscore = 0;








while (letter != 'x')





{


cout%26lt;%26lt;"How many scores are you entering?"%26lt;%26lt;endl;


cin%26gt;%26gt;num1;





for (int counter=0; counter%26lt;num1;counter++)


{


{


cout%26lt;%26lt;"Enter an integer: "; cin%26gt;%26gt;scores;





cout%26lt;%26lt;endl;


}





oddcount = ( ( scores % 2) != 0);





oddcount++;





if ( scores %26gt; highestscore )





highestscore = scores;





}


cout%26lt;%26lt;"You entered "%26lt;%26lt;oddcount%26lt;%26lt;" odd numbers."%26lt;%26lt;endl;


cout%26lt;%26lt;"The highest # is "%26lt;%26lt;highestscore%26lt;%26lt;endl;


cout%26lt;%26lt;"Finish...press 'x' to exit program. any other key to run again."%26lt;%26lt;endl;


cin%26gt;%26gt;letter;


}

Easy Basic C++ Programming Help?
try setting oddcount and highestscore to 0 right after while (letter != 'x')





then replace





oddcount = ( ( scores % 2) != 0);


oddcount++;





with





oddcount += ((scores %2) != 0);





each time through the for loop oddcount is being reset to 0 or 1, and then incremented. So your answer output by oddcount will always be 1 or 2, even if you put in 100 odd numbers. The += adds the 0 or 1 to the previous value of oddcount.
Reply:Your code looks a bit incomplete? I'm guessing that there was another while statement at the top?





If you move the int declarations out of the outer while loop but still do the assignments inside that while loop it might work. I'm not sure of the theory but I have a feeling that the initialisations will only be done the first time if you declare the variables and assign to them at the same time.


No comments:

Post a Comment