Search code examples
c++vectortype-conversionsfmlnarrowing

Invalid narrowing conversion from "float" to "int"


I am using the SFML graphics library for C++. My compiler is Visual Studio 2017.

When I was making the function scale I encountered a problem. I had an error saying:

Invalid narrowing conversion from "float" to "int"

So, I put roundf in front of both items in the vector, but this didn't seem to help. Changing the std::vector<int> to std::vector<float> for the return value seems to work but I would like it as an integer. Any ideas? Here's my code:

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

Solution

  • You want lroundf() to convert to a long int rather than round() which returns a float. You may also need to cast the result of lroundf() to int (because that is usually narrower than long).

    Like this:

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