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
当我将 x 和 y 打印到控制台时,它会给我一些疯狂的数字。似乎将 long 转换为 float 会丢失一些数据,但为什么呢?它应该没有任何问题。
它打印:
x: 0, y: 1080795136
最佳答案
sprintf_s(buf, "x: %d, y: %d\n", x,y);
应该是
sprintf_s(buf, "x: %f, y: %f\n", x,y);
因为x
和y
是float
类型,不是整数。
关于c++从long转换为float奇怪的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16907270/