在 C++ 中将正浮点数组转换为带舍入的无符号短数组
convert a positive float array to an unsigned short array with rounding in C++
我有一个正浮点数数组,想将此数组转换为带舍入的无符号短数组。我怎样才能有效地做到这一点?这是一个例子:
float floatArr[] = {1.2, 1.8, 2.1, 2.5, 3.2};
unsigned short usArr[5];
// I could do this
std::copy(floatArr, 5, usArr);
但是,它只会进行转换,因为它基本上是复制前两个字节。所以结果是usArr[] = {1, 1, 2, 2, 3}
。我的问题是如何将这个带舍入而不是强制转换的浮点数组转换为 usArr[] = {1, 2, 2, 3, 3}
?谢谢,如果有任何帮助,我将不胜感激!
您似乎想要四舍五入而不是向下舍入 std::round
可以帮助您解决这个问题。使用std::transform
一步取整复制:
#include <algorithm>
#include <iostream>
#include <cmath>
int main()
{
float floatArr[] = {1.2, 1.8, 2.1, 2.5, 3.2};
unsigned short usArr[5];
// (1) Using a lambda to choose correct overload:
std::transform(floatArr, floatArr + 5, usArr, [](float f){ return std::round(f); });
// (2) Using static cast to enforce that specific overload is called:
std::transform(floatArr, floatArr + 5, usArr, static_cast<float(*)(float)>(std::round));
for(int i = 0; i < 5; ++i)
std::cout << usArr[i] << ' ';
}
我有一个正浮点数数组,想将此数组转换为带舍入的无符号短数组。我怎样才能有效地做到这一点?这是一个例子:
float floatArr[] = {1.2, 1.8, 2.1, 2.5, 3.2};
unsigned short usArr[5];
// I could do this
std::copy(floatArr, 5, usArr);
但是,它只会进行转换,因为它基本上是复制前两个字节。所以结果是usArr[] = {1, 1, 2, 2, 3}
。我的问题是如何将这个带舍入而不是强制转换的浮点数组转换为 usArr[] = {1, 2, 2, 3, 3}
?谢谢,如果有任何帮助,我将不胜感激!
您似乎想要四舍五入而不是向下舍入 std::round
可以帮助您解决这个问题。使用std::transform
一步取整复制:
#include <algorithm>
#include <iostream>
#include <cmath>
int main()
{
float floatArr[] = {1.2, 1.8, 2.1, 2.5, 3.2};
unsigned short usArr[5];
// (1) Using a lambda to choose correct overload:
std::transform(floatArr, floatArr + 5, usArr, [](float f){ return std::round(f); });
// (2) Using static cast to enforce that specific overload is called:
std::transform(floatArr, floatArr + 5, usArr, static_cast<float(*)(float)>(std::round));
for(int i = 0; i < 5; ++i)
std::cout << usArr[i] << ' ';
}