Question:

If the answer of this perticular problem 300*300/300 is 81 in 'C' lang. then plz tell me anyone how?

by  |  earlier

0 LIKES UnLike

If the answer of this perticular problem 300*300/300 is 81 in 'C' lang. then plz tell me anyone how?

 Tags:

   Report

2 ANSWERS


  1. Mikey's totally correct.  You're probably using a two byte integer to store the answer.  A little more detail about what it's probably doing:

    300 = 0000000100101100 (9 bits required)

    300 * 300 = 90000 = 10101111110010000 (17 bits required! Uh oh!)

    So, because it won't fit into 16 bits, you lose the 1st bit, which is set to a 1.  You might actually be losing the 1st two bits, if it's a signed short value, but we can't be sure.  Anyway, your result gets truncated into 16 bits:

    0101111110010000 = 24464

    Next, when you divide by 300, you get:

    24464 / 300 = 81.54666...

    And since it's not a floating point number, it's truncating it to 81.  You may be able to avoid this problem by changing your calculation to:

    300*(300/300)

    That's mathematically the same, but won't overflow the bytes.  

    DaveE


  2. What is happening is that the compiler is storing the intermediate result of 300 * 300 into a short int (2 bytes), which in turn cannot hold the result. So, when the result is divided by 300, you get 81.

    The short int result of 300 * 300 = 0x5F90     = 24464

    24464 / 300 = 81.54, but the fraction gets dropped since we are dealing with integers.

    The int result of 300 * 300         = 0x15F90   = 90000

    90000 / 300 = 300

Question Stats

Latest activity: earlier.
This question has 2 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.