Vinícius
Vinícius

Reputation: 15718

percentage function calculating abnormal value

In the following function I'm receiving abnormal values.

(Please disconsider hungarian notations, I'm following rules of an old source)

int nMaxHP = m_pDefender->GetMaxHitPoint();
u_long nPercentHP = 0;
if( nMaxHP > 0 )
    nPercentHP = (  nHP * 100 ) / nMaxHP;

CString show;
show.Format( "%u %d %d", nPercentHP, nMaxHP, nHP );
pUserAttacker->AddTextD3D( show, 0xffff0000 );

This is part of a damage code on a game client, m_pDefender is the big lion pillar, nHP is the hitpoints he has after taking damage and nMaxHP is self-explanatory. AddTextD3D( CString format, DWORD color ) shows a message as you can see on the image. Screenshot

The thing is,
34.000.000 = nMaxHP
33.999.999 = nHP

33.999.999 * 100 = 3.399.999.900
3.399.999.900 / 34.000.000 = 99 (or 99.99999705882353 on double precision)

The question is why nPercentHP is 4294967270?

Upvotes: 2

Views: 187

Answers (1)

6502
6502

Reputation: 114461

Your computation is exceeding the 32-bit arithmetic maximum value.

Convert first everything to double

Upvotes: 4

Related Questions