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

标签 c++ casting window

        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); 

因为xyfloat 类型,不是整数。

关于c++从long转换为float奇怪的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16907270/

相关文章:

C++ 分数类

objective-c - 设置窗口的最小和最大尺寸

emacs - 如何让编译日志在 Emacs 中创建一个新窗口?

c# - 从 "TimeSpan"转换为 "Long"

java - 将基类从java中的反序列化集合转换为继承类

javascript 相对于窗口大小调整内容大小

c++ - 如何结束 C++ 代码

c++ - 从派生类构造函数初始化 protected 数据成员

c++ - 制作迭代器的拷贝是个坏主意吗?

c++ - C->C++ 在未给出类型的情况下,在#define 中自动将 void 指针转换为 C++ 中的类型指针(C 风格)[MSVS]