c++从long转换为float的奇怪错误
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: %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);
因为x
和y
是float
型,而不是整数。
如果您使用%d格式并传递浮点数(实际上是作为double传递),那么毫无疑问您会得到垃圾。你可能会变得更糟。尝试%f格式,或转换为%d所期望的int。
修改为
sprintf_s(buf, "x: %f, y: %fn", x,y);
因为你正在使用浮点数
可能是因为你在sprintf_s调用中使用了%d吗?尝试使用%f来代替,看看这是否是问题所在。
相关文章:
- 为什么我会收到此错误?无法将 {lb, ub} 从<大括号括起来的初始值设定项列表>转换为 float(**)(float*, int)
- 错误:二进制'operator*' 'float'和'float[0]'类型的操作数无效
- 编译器给出错误:format 指定类型 'float *',但参数的类型'double' [-Wformat]
- 错误:无法将"float*"转换为"float"
- 我一直收到错误"cannot convert 'float*' to 'float' in return"
- 谷歌测试编译错误 Os X:函数式转换从"int"到"internal::FloatingEq2Matcher"的模糊转换<float>
- "错误:数组下标的无效类型'float [10001][float]'是什么意思?
- Sizeof(float) 在 atmega2560 上给出错误的结果
- 错误:'float'之前的预期主表达式
- 错误:二进制表达式('float' 和 'float')返回的无效操作数 (x & (1 << 31)) == 0
- 错误:无法将参数"1"的"float*"转换为"float"
- 错误:二进制'operator*' 'int [1]'和'float'类型的操作数无效
- 转换特征矩阵类型时,错误:在"float"之前预期主表达式
- 此背包代码显示浮点[float]无效类型错误.可能是什么原因
- 错误:C++ 中二进制"operator%"类型"float"和"int"的操作数无效
- C++ 错误:不存在从 "math::Vec3<float>" 到 "float" 的合适转换函数
- Waht [错误] 请求 memebr 'area' 在非类类型 'float' 中'r'是什么意思?
- QML/real和C++/float之间的Qt类型错误
- 简单继承实现中的构建错误"expected primary-expression before 'float' "来源
- 使用boost multiprecision/mpfr float-字符串不能被解释为有效的整数错误