c++从long转换为float的奇怪错误

c++ convert from long to float weird error

本文关键字:错误 float long 转换 c++      更新时间:2023-10-16
        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: %dn", x,y); // create string to print
        OutputDebugStringA(buf); // print to debut window

当我将x和y输出到控制台时,它会给我一些疯狂的数字。似乎将long转换为float会丢失一些数据,但为什么呢?应该不会有任何问题的。

它打印:
X: 0, y: 1080795136

 sprintf_s(buf, "x: %d, y: %dn", x,y); 
应该

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

因为xyfloat型,而不是整数。

如果您使用%d格式并传递浮点数(实际上是作为double传递),那么毫无疑问您会得到垃圾。你可能会变得更糟。尝试%f格式,或转换为%d所期望的int。

修改为

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

因为你正在使用浮点数

可能是因为你在sprintf_s调用中使用了%d吗?尝试使用%f来代替,看看这是否是问题所在。

相关文章: