简体   繁体   English

从 int 到 float 的转换是否比 static_cast 更优雅<float> ?</float>

[英]Is there a more elegant cast from int to float than static_cast<float>?

I'm a .NET developer trying to do c++ (ahem) and I encountered a compiler warning in here:我是一名 .NET 开发人员,试图做 c++(咳咳),我在这里遇到了编译器警告:

const auto u = (textel.character % font_glyph_column_count) * font_glyph_size; // <- all int
const auto v = (textel.character / font_glyph_column_count) * font_glyph_size; // <- all int
const auto top_left_uv = sf::Vector2f(u, v);

In the last line, where 'u' and 'v' are passed as args to the Vector ctor, the compiler says:在最后一行,“u”和“v”作为参数传递给 Vector ctor,编译器说:

conversion from 'const int' to 'T', possible loss of data从 'const int' 到 'T' 的转换,可能会丢失数据

Ok, .NET doesn't do this, but i looked it up and i understand that not all int32 can be represented by a float.好的,.NET 没有这样做,但我查了一下,我知道并非所有的 int32 都可以用浮点数表示。 (Now I wonder why .NET doesn't warn about this:) ) (现在我想知道为什么 .NET 没有对此发出警告:))

So, my .NET inspired solution is - apparently called - a "C cast", which my Resharper complains about: so, i change it to a static_cast.所以,我的 .NET 启发解决方案是 - 显然被称为 - “C cast”,我的 Resharper 抱怨说:所以,我将其更改为 static_cast。 Okido...冲户...

const auto u = static_cast<float>(textel.character % font_glyph_column_count) * font_glyph_size;
const auto v = static_cast<float>(textel.character / font_glyph_column_count) * font_glyph_size;
const auto top_left_uv = sf::Vector2f(u, v);

But yuk, now my arithmetic code gets littered with these casts, while the juggling around of integer computation is very deliberate, and having to put the result in float-based vectors.但是,哎呀,现在我的算术代码被这些演员乱扔了,而 integer 计算的杂耍是非常慎重的,并且必须将结果放入基于浮点数的向量中。 is also necessary...也是必须的……

I could change eg.我可以改变例如。 font_glyph_size to a float, so casting becomes implicit, but it makes more sense for it to be a discrete amount of pixels, so int... font_glyph_size 为浮点数,因此转换变得隐式,但将其作为离散数量的像素更有意义,因此 int ...

Can this code be made prettier?这段代码可以变得更漂亮吗?

You can use c stryle cast.您可以使用 c 串铸。

int a = 1;整数a = 1; float b = (float) a;浮动 b = (浮动) a;

Also you can do just你也可以做

int a = 1;整数a = 1; float b = a;浮动 b = a;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM