簡體   English   中英

在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} 我的問題是我該如何將舍入而不是轉換的float數組轉換為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] << ' ';
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM