How is the standarized way to calculate float with integers?

后端 未结 3 1039
日久生厌
日久生厌 2021-01-24 12:14

Do any of you know how this will be calculated in C?

uint8_t samplerate = 200;
uint8_t Result;
Result = 0.5 * samplerate;

Now, the problem is t

3条回答
  •  余生分开走
    2021-01-24 12:48

    Yes, there is a standard. In this case, the numbers in the expression are automatically converted to the wider type (one that occupies more bytes), so your expression will be evaluated as follows:

    (0.5: double) * (0: uint8_t) => (0.5: double) * (0.0: double) == (0.0: double)
    uint8_t Result = (0.0: double) => (0: uint8_t) // this is a forced cast, because Result is of type uint8_t
    

    double is wider than uint8_t, so (0: uint8_t) is widened to (0.0: double). This cast doesn't lose information since double occupies enough space to fit all the data stored in uint8_t.

提交回复
热议问题