Alexander
Alexander

Reputation: 510

Why do I have different results by casting values

I'm really wasting a lot of time solving a problem in my code. Now it is working, but I do not understand what is going wrong.

Using QT5 / gcc

int pos;
uint m_endZeit, m_startZeit;

float secPerPx = (pos * (m_endZeit - m_startZeit)) / static_cast<float>(width());
uint a = secPerPx + m_startZeit;
uint b = static_cast<uint>(secPerPx) + m_startZeit;
std::cout << a << " vs. " << b << std::endl;    

Output:

1404809856 vs. 1404809893

Can anyone explain this to me? Why is this not the same?

Upvotes: 1

Views: 72

Answers (1)

Bur0k
Bur0k

Reputation: 136

What range of numbers can be represented in a 16-, 32- and 64-bit IEEE-754 systems?

The Precision of a float is roughly 8-9 digits and you already have 10.

uint a = secPerPx + m_startZeit;

The above code first casts m_startZeit to a float, adding the 2 values and then casts it back to an Integer.

uint b = static_cast<uint>(secPerPx) + m_startZeit;

This is casting the float to an integer BEFORE they both get added together.

Upvotes: 3

Related Questions