tectona 0 Posted October 14, 2005 Report Share Posted October 14, 2005 Hi, I found one problem in my program. " .... unsigned int a; unsigned int b; signed int c; ..... c = (((b-a)*100)/:D; // Equation 1 c = (b-a); c = (c*100); c = (c/B); //Equation 2 ..... " In Equation 1 & 2 Logically same. But during debug i found both ans differ from each other. If i put a = 80 & b = 9 then c is: Ans. of Equation 1 is 0x195c Ans. of Equation 2 is 0xfcec I use Boostc 6.11 . Why ? Regards Tectona Quote Link to post Share on other sites

Dave 0 Posted October 14, 2005 Report Share Posted October 14, 2005 tectona, What answer to you expect to get? I cant see how you would get either! Please post a complete code example. Regards Dave Quote Link to post Share on other sites

pittuck 0 Posted October 15, 2005 Report Share Posted October 15, 2005 c = (((b-a)*100)/b); // Equation 1 c = (b-a); c = (c*100); c = (c/b); //Equation 2 [assuming a and b are decimal] Lets take Equation 2: c (which can be negative) = (b-a) = (9 - 80) = -71 (i will do the 2s compelment at the end) c = (c * 100) = -71 * 100 = -7100 c = (c / 9) = -7100 / 9 = -788.9 = 0xFCEC But with EQ 1 (b-a) will be somming like 0xFFB9 as it cannot go negative, hence there is an error (a unsigned int - unsigned int = unsigned int to the compiler) Quote Link to post Share on other sites

DarrenJ 0 Posted October 19, 2005 Report Share Posted October 19, 2005 (edited) tectona c = (((b-a)*100)/b); // Equation 1 c = (b-a); c = (c*100); c = (c/b); //Equation 2 I think you will find that in equation 1 all the stuff on the right hand side is performed at the precision of the variables on the right hand side; ie a and b, so unsigned int. When the calculations are finished the result is converted to a signed int and assigned to c. In the second calculation the subtration is correctly converted to a signed int in the first statement. Then the second and third statements are performed at a signed int level instead of an unsigned int. I think?? this is C standard behaviour. I also think that if you want to change it, you can just cast it to an signed int eirlier. (NB: I haven't tried on this compiler) c = ((((signed int)(b-a))*100)/b); or use; signed int d; signed int e; d = a; e = b; c = (((e-d)*100)/e); or step it through as in your second example. c = (b-a); c *= 100; c /= b; perhaps it might also work like: c = (b-a); c = (c*100)/b; As there is a signed int on the right, but I would have to read my C books again (and the compiler docs) to check that one. Hope that helps. Darren J Edited October 20, 2005 by DarrenJ Quote Link to post Share on other sites

## Recommended Posts

## Join the conversation

You are posting as a guest. If you have an account, sign in now to post with your account.

Note:Your post will require moderator approval before it will be visible.