Tuesday, July 14, 2009

C++ problem?

How do I tell the program that the last number entered was the same.


#include%26lt;stdio.h%26gt;





int


main()


{





int a, b, c, d, e, total;





printf ("Enter a number : "); /*recieve first number*/





scanf ("%d",%26amp;a);





if (a%2==0)


{


printf ("The entered number is EVEN.\n");





}


else


{


printf ("The entered number is ODD.\n");





}





printf ("Enter a number : "); /*second number*/





scanf ("%d",%26amp;b);





if (b%2==0)


{


printf ("The entered number is EVEN.\n");





}


else


{


printf ("The entered number is ODD.\n");





}


if ("%d=%d", b, a);


{


printf("That is the same number.\n");


}


This is only part of the program. If i enter 3 first than 4 it says I just entered the same number. I think by using 'if' I need to use 'else'.


I want it to tell the user that they entered the same number as the number previous when they actually do.

C++ problem?
you're incorrectly using the "=" The single "=" means you set a varible to the next.





Since you're using c++ you can use if (a==b). That will compare a and b.





a=b makes the varible a equal to b.





As good programming practice you should give your variables meaningful names. ie. Num1 and Num2 instead of a and b
Reply:In your another post I couldn't find a "answer to this question" button, anyway yes you must use: printf or cout to print out.





In c/c++ for equality comparision you must use "==".


In your code you had written:





if ("%d=%d", b, a);


{


printf("That is the same number.\n");


}





but the correct form is as follows:





if (b==a);


{


printf("a and b are equal.\n");


}
Reply:The problem is you have a semicolon after your if statement.


if ("%d=%d", b, a);


Also, your if statement doesn't make sense. You need to use:


if(a == b), which means if a equals b. a = b in C will assign a to b, and it will always be true unless b is equal to 0.


That will always terminate the if. You won't need an else statement.





Good luck!


No comments:

Post a Comment