Home > database >  How to calculate float value and then convert to uint8_t?
How to calculate float value and then convert to uint8_t?

Time:12-01

How to calculate float value and then convert to uint8_t? As below, the current progress is 50, but overall just 50% completed, the correct value is 25, but I got 0.

#include <iostream>

using namespace std;

int main()
{
    uint8_t remaining = 1;
    uint8_t total = 2;
    uint8_t progress=50;
    float value=0;

    value = (float)(total-remaining)/total;
    progress = (uint8_t)value*progress;
    cout<<"value:"<<value<<endl;
    cout<<"progress:"<<(unsigned)progress<<endl;

    return 0;
}

The result are:

value:0.5
progress:0

How to get the correct 25?

CodePudding user response:

The (C-style) cast has higher precedence than multiplication, so your progress = (uint8_t)value*progress statement is evaluated as progress = ( (uint8_t)value ) * progress;. Thus, the 0.5 in value (from the previous line) will be truncated to zero.

You need to put the multiplication in parentheses. Also, try to avoid using C-style casts:

progress = static_cast<uint8_t>(value * progress);

CodePudding user response:

At the line where you update the progress, you are signaling cpp to interpret the value as an uint8_t and then multiply it by progress. So the system is truncating value to an integer and then performing the product.

In order to fix it, you first want to multiply and then reinterpret:

    progress = (uint8_t)(value * progress);

So adding the parenthesis will give priority to the product.

Also, you should avoid using c-style casts in cpp code:

Because the C-style cast (T) can be used to express many logically different operations, the compiler has only the barest chance to catch misuses. For the same reason, a programmer may not know exactly what a cast does. This is sometimes considered an advantage by novice programmers and is a source of subtle errors when the novice guessed wrong.

So the correct way of doing it would be:

    progress = static_cast<uint8_t>(value * progress);

  •  Tags:  
  • c
  • Related