Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to calculate float value and then convert to uint8_t?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading