【问题标题】:Invalid narrowing conversion from "float" to "int"从“float”到“int”的无效缩小转换
【发布时间】:2018-01-13 11:35:30
【问题描述】:

我正在使用 C++ 的 SFML 图形库。我的编译器是 Visual Studio 2017。

当我在制作函数scale时遇到了一个问题。我有一个错误说:

Invalid narrowing conversion from "float" to "int"

所以,我将roundf 放在向量中两个项目的前面,但这似乎没有帮助。将返回值的std::vector<int> 更改为std::vector<float> 似乎可行,但我希望它是一个整数。有任何想法吗?这是我的代码:

std::vector<int> scale(sf::RenderWindow *Window, std::vector<int> offset)
{ // Scale objects
    float scale = 500;
    return { roundf(Window->getSize().x / scale * offset[0]), roundf(Window->getSize().y / scale * offset[1]) };
}

【问题讨论】:

    标签: c++ vector type-conversion sfml narrowing


    【解决方案1】:

    您希望 lroundf() 转换为 long int 而不是返回浮点数的 round()。您可能还需要将lroundf() 的结果转换为int(因为它通常比long 窄)。

    像这样:

    return { int(lroundf(Window->getSize().x / scale * offset[0])), int(lroundf(Window->getSize().y / scale * offset[1])) };
    

    【讨论】:

    • 谢谢!我将其更改为 lroundf(),但不需要 int()。问题解决了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-02
    • 1970-01-01
    • 1970-01-01
    • 2020-06-20
    • 2017-02-19
    • 2020-01-15
    • 2012-05-13
    相关资源
    最近更新 更多