Monday, May 24, 2010

Whats wrong with this c++ program?

I need to output the sum of the square of the odd numbers between firstnum and secnum. I also need to output the sum of all the even numbers between firstnum and secnum.





#include%26lt;iostream%26gt;


#include%26lt;cmath%26gt;


using namespace std;


int main()


{


int firstnum,secnum, i, total=0, a, b;


cout%26lt;%26lt;"Enter a integer:";


cin%26gt;%26gt;firstnum;


cout%26lt;%26lt;"Enter a second integer (must be less then the first integer enterd):";


cin%26gt;%26gt;secnum;


cout%26lt;%26lt;"your enterd :"%26lt;%26lt;secnum%26lt;%26lt;endl;


if(firstnum%26lt;secnum)


cout%26lt;%26lt;endl;


else


if (firstnum%26gt;secnum)


cout%26lt;%26lt;"Please re-run program and enter numbers again"%26lt;%26lt;endl;


for (i=firstnum; i%26lt;= secnum; i++)


if(i % 2 != 0)


cout %26lt;%26lt; i %26lt;%26lt; " is an odd number between " %26lt;%26lt; firstnum %26lt;%26lt; " and " %26lt;%26lt; secnum %26lt;%26lt; endl;


cout%26lt;%26lt;"The sqrt is"%26lt;%26lt;sqrt(i)%26lt;%26lt;endl;





for (i=firstnum; i%26lt;= secnum; i++)


if(i % 2 == 0)


cout %26lt;%26lt; i %26lt;%26lt; " is an even number between " %26lt;%26lt; firstnum %26lt;%26lt; " and " %26lt;%26lt; secnum %26lt;%26lt; endl;


total += i;


cout %26lt;%26lt; "The total of all even numbers from " %26lt;%26lt; firstnum %26lt;%26lt; " to " %26lt;%26lt; secnum %26lt;%26lt; " is " %26lt;%26lt; total %26lt;%26lt; endl;


cout%26lt;%26lt;"\nPart B"%26lt;%26lt;endl;


a=1;


while(a%26lt;=10)


{


cout%26lt;%26lt;a%26lt;%26lt;" the sqrt "%26lt;%26lt;sqrt(a)%26lt;%26lt;endl;


a=a+1;


}


system("pause");


return 0;

Whats wrong with this c++ program?
There are numerous problems, but I believe these are the three most important ones:





I. It doesn't follow the specification


As written, your program looks like it was supposed to output the following:


1. The odd numbers between firstnum and secnum.


2. The square roots of those numbers.


3. The even numbers between firstnum and secnum.


4. The sum of all the even numbers between firstnum and secnum


5. The square roots of the whole numbers 1 through 10.


Of those 5 things, only one (number 4) is among the things you originally said the program is supposed to output.





II. For loops need correction


If you want several statements to be executed on each iteration of a for loop, you have to put those statements inside curly braces, like this:


for (i = firstnum; i %26lt;= secnum; i++)


{


(the statements go here)


}


Otherwise, only the first statement after the for statement is executed on each iteration of the loop.





III. Numbers aren't squared correctly


If you want the square, as opposed to the square root, of a number a, then you need to use a**2 or a*a, not sqrt(a).


No comments:

Post a Comment