Sunday, August 2, 2009

C++ help me please?

Here's my code:





#include %26lt;iostream%26gt;


using namespace std;





int main()


{


int i = 0, max = 0, sum = 0;


char indicator = 'y';


cout%26lt;%26lt;"Please enter number 5: "; cin%26gt;%26gt;max;


cout%26lt;%26lt;endl;


for(i=1; i%26lt;=max; i++)


sum+=i;


cout%26lt;%26lt;endl


%26lt;%26lt;"The Sum is = "%26lt;%26lt;sum%26lt;%26lt;endl;


cout%26lt;%26lt;"Do you wish to display the odd sum?"%26lt;%26lt;endl;


cout%26lt;%26lt;"Enter y for yes, (n to end)"; cin%26gt;%26gt;indicator;


if(indicator=='y')


{


for(i=1; max%26lt;=max; i=1+2)


sum=sum+i;


cout%26lt;%26lt;endl


%26lt;%26lt;"The odd sum is = "%26lt;%26lt;sum%26lt;%26lt;endl;


}


cout%26lt;%26lt;"Okay Bye"%26lt;%26lt;endl;


return 0;


}





The answer for the 1st sum is correct 15


But the Odd sum answer should be 9 and it's aint displaying and wrong answer.

C++ help me please?
You forgot to re-initialize sum. It's adding 9 to 15 and giving you 24, right? And yeah, I missed it, but you also need to have i = i + 2, not i = 1 + 2.





if(indicator=='y')


{


sum = 0;


for(i=1; max%26lt;=max; i=i+2)


sum=sum+i;


cout%26lt;%26lt;endl


%26lt;%26lt;"The odd sum is = "%26lt;%26lt;sum%26lt;%26lt;endl;


}
Reply:for(i=1; max%26lt;=max; i=1+2)





That is very wrong there, check your study material what is not right.
Reply:I never got to C++, but do you want i=3 or do you want i=i+2?


Your line is:


for(i=1; max%26lt;=max; i=1+2)


, which would always make i=3.
Reply:Yeah, i have to agree with some of the other answers.





sum needs to be reinitialized to 0 before the second for loop.





the second for loop looks funky to me. Especially the condition max%26lt;=max and i=1+2.
Reply:Two problems:





You need to add a line that zeros your sum for the second accumulation:





if(indicator=='y')


{


sum=0; // NEW LINE TO RESET SUM


for(i=1; max%26lt;=max; i=1+2)








And the line :





for(i=1; max%26lt;=max; i=1+2)





Needs to be re-written:





for(i=1;i%26lt;=max;i+=2) // NOT max%26lt;=max and NOT i=1+2


No comments:

Post a Comment