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?
>Solution :
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);