Sunday, August 2, 2009

Basic C++ Programming Help?

I am trying to figure out 3 simple things that I really can't figure out...





1) total odd numbers for my program when I input "3" scores of 53,54,67.


2) determine the highest number between those scores which is "67" .


3) How do I end the program by pressing "x" at the end, but it starts over when I press any other letter





#include %26lt;iostream%26gt;





using namespace std;





int main()


{





int counter = 1;


int totalodd = 0;


int num1;


int scores;


char letter;


int numbers;





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


cin%26gt;%26gt;num1;





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


cout%26lt;%26lt;"Enter an integer: "%26lt;%26lt;endl;


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


cin%26gt;%26gt;scores;





if ( ( scores % 2) != 0 )


totalodd = totalodd + scores;





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


totalodd++;





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

Basic C++ Programming Help?
The obvious bug I see is that your for() loops only apply to the next statement. If I enter 3 at the first prompt, you will execute the cout 3 times (showing the prompt over and over) then ask for a number 3 times, overwriting the first 2, then do the calculation on the last number only.





You need to group the prompt (cout0, cin, and calculation all within each pass of the loop by using { and } correctly.





Try:


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


{


cout%26lt;%26lt;"Enter an integer: "%26lt;%26lt;endl;





cin%26gt;%26gt;scores;





if ( ( scores % 2) != 0 )


totalodd = totalodd + scores;


}
Reply:A second issue is that you need to store the highest value somewhere, maybe in a variable named "highest". After the first value gets read into "scores", assign that as the highest value, for later values you must compare to the previous highest:





if (counter == 1) // 1st value is highest by default


highest = scores;


else if (scores %26gt; highest) // later values get compared to previous highest


highest = scores; // if new value%26gt;previous highest, then make that the highest


No comments:

Post a Comment