将整数除法存储在浮点值C ++中 [英] Store division of integers in float value C++

查看:53
本文介绍了将整数除法存储在浮点值C ++中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想问一下,如果我不像这样将浮点数存储在浮点数中时,我不强制转换浮点数,会发生数字明智的事情:

I just wanted to ask what happens number wise if i do not typecast integers to float when storing in a float variable like this:

int32 IntVar1 = 100
int32 IntVar2 = 200
float FloatVar = IntVar1/IntVar2;

目前我正在这样做:

int32 IntVar1 = 100
int32 IntVar2 = 200
float FloatVar = float(IntVar1)/float(IntVar2);

但是在我拥有的代码数量上,这看起来确实很困难.我曾考虑过将int变量更改为float,但是我想那会影响性能.而且由于整数值不应包含任何小数,因此感觉像是完全浪费.

But in the amount of code i have, this looks really retarded. I thought about changing my int variables to float, but i guess that would be a performance hit. And since the integer values are not supposed to hold any decimals, it feels like a complete waste.

所以我想知道,选项1是否有可能起作用?还是我必须进行类型转换或将变量更改为浮点数?(所有类型转换几乎都使代码不可读)

So i wonder, are there any way that option 1 could be working? Or do i have to typecast OR change variables to float? (All typecasting pretty much makes the code unreadable)

推荐答案

看到功能的魔力:

float div(int x, int y)
{
    return float(x) / float(y);
}

现在您可以说:

int32 IntVar1 = 100
int32 IntVar2 = 200
float FloatVar = div(IntVar1, IntVar2);

这篇关于将整数除法存储在浮点值C ++中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆