Monday, May 24, 2010

Can anyone help me with this c program?

void main()


{


unsigned i=1;


signed j=-1;


if(i%26lt;j)


printf("less");


else


if(i%26gt;j)


printf("greater");


else


if(i==j)


printf("equal");


}








o/p is less





can anyone help me how this works?

Can anyone help me with this c program?
Indeed.





To those of you who didn't bother to understand the question, this program works, but says that 1 %26lt; -1, which is not right.





The problem is "signedness" - when comparing signed and unsigned integers, the C complier casts both numbers to unsigned, which turns (-1) into 4294967295 (unsigned representation of -1).





Try this to see what I'm talking about:





void main()


{


unsigned i=1;


signed j=-1;


if(i%26lt;j)


printf("less %u %26lt; %u", i, j);


else


if(i%26gt;j)


printf("greater %u %26gt; %u", i, j);


else


if(i==j)


printf("equal");


}








To avoid this ambiguity, tell the compiler explicitly how you want it to treat your numbers - as singed or unsigned, i.e.:





if ( (signed) i %26lt; (signed) j)





or





if ( (unsigned) i %26lt; (unsigned) j)
Reply:Sure,





//ur program enters the main method here...


void main()


{


//u assign 2 variables i and j


unsigned i=1;


signed j=-1;


//this asks if i is less than j which it is not so it goes to the else


if(i%26lt;j)


printf("less");


//this asks if i is greater than j which it is so it runs the code in the else block


else


if(i%26gt;j)


//this tells it to print greater


printf("greater");


else


//because the code went into the above else block it will not bother to check this if statement..


if(i==j)


printf("equal");


}
Reply:Means: if i is less than j, print less


if i is more than j, print more


if i is equal to j, print equal


If u need any more help, email me: pravin.singh71@yahoo.com





(was that your homework)
Reply:It goes something like this.....





if i is less than j, then print "Less" to the screen.


if i is more than j, then print "more" to the screen.


if they are equal, then print "equal" to the screen.





I hope I didn't just do your homework for you and no, you don't have my permission to copy and paste it, if you're gonna cheat at least type it in yourself.

easter cards

No comments:

Post a Comment