Anthony Raimondo
Anthony Raimondo

Reputation: 1721

c++ convert from long to float weird error

        POINT p;
        RECT rec;

        ::GetClientRect(hWnd, &rec);
        LONG windowWidth = rec.right, windowHeight = rec.bottom;

        ::GetCursorPos(&p);//get position on screen
        ::ScreenToClient(hWnd,&p);//convert POINT to position in window

        // 2d vector math
        float x=0.0f,y=0.0f; // vector
        x= static_cast<float>(p.x - (windowWidth>>1)); // problem...
        y= static_cast<float>(p.y - (windowHeight>>1));

        char buf[100];
        sprintf_s(buf, "x: %d, y: %d\n", x,y); // create string to print
        OutputDebugStringA(buf); // print to debut window

when i print x and y to the console it give me crazy numbers. it seems that casting long to float is losing some data, but why? there shouldnt be any problems with it.

it prints:
x: 0, y: 1080795136

Upvotes: 0

Views: 165

Answers (4)

Tcz
Tcz

Reputation: 701

Just modify to

sprintf_s(buf, "x: %f, y: %f\n", x,y);

because you are using floats

Upvotes: 3

Balog Pal
Balog Pal

Reputation: 17223

If you use %d format and pass a float (that is actually passed as double), no wonder you get garbage. You could get way worse. Try %f format, or convert to the int expected by %d.

Upvotes: 3

taocp
taocp

Reputation: 23664

 sprintf_s(buf, "x: %d, y: %d\n", x,y); 

should be

 sprintf_s(buf, "x: %f, y: %f\n", x,y); 

since x and y are float type, not integers.

Upvotes: 5

Joe Runde
Joe Runde

Reputation: 253

Could it be because you're using %d in your sprintf_s call? Try using %f instead and see if that's the issue.

Upvotes: 2

Related Questions