Thursday, July 30, 2009

I keep on getting an error when I compile c++ program?

I am kind of new to programming so please don't criticize me. This is the source code for the program I am trying to build:











#include %26lt;iostream%26gt;


using namespace std;








int main()


{


float a;


cout %26lt;%26lt; "enter a number";


cin %26gt;%26gt; a;





if (a%2 == 0)


{


cout %26lt;%26lt; "the number is even";


}


else


{


cout %26lt;%26lt; "the number is odd";


}





return 0;


}








this program should allow the user to input a number and it will tell them if it is even or odd. yet when I try to compile this code, my IDE displays the following error:





invalid operands of types ‘float’ and ‘int’ to binary 'operator%'

I keep on getting an error when I compile c++ program?
Perhaps





if (a % 2.0 == 0)
Reply:It is not possible to perform modulus on float, it's not always clear what the right answer is, nor does it have any logical basis (modulus does with real integers). Plus the loss from precision makes it not very useful, I can't think of a time when you would want to do that.
Reply:make your a an int





int a;
Reply:the previous answer made by BM is correct, you should then write a rule that prevents decimal statements from being entered, something to teh effect of;


int a;


do {


cout %26lt;%26lt;"Enter a number.\n";


cin %26gt;%26gt; a;


}while(a%1 != 0);


No comments:

Post a Comment