将int隐式转换为double [英] Implicitly converting int to double

查看:208
本文介绍了将int隐式转换为double的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有点困惑。我认为这应该可行:
在这种情况下, a b 都是整数(准确地说是计数器)。

So, I'm a tad confused. I was under the impression that this should work: In this case, both a and b are ints (Counters to be exact).

由于 a / b 的结果可能包含小数位,因此整数显然不起作用。
因此,我对一个新的double进行了延迟,并在其中执行了如下计算:

As the result of a / b may possibly contain decimal places, ints obviously won't work. Therefore, I delared a new double and performed the calculation inside it like this:

double texturefactor = ((a / b) * 10);

这不符合我的预期, a 的结果/ b 始终是我使用int进行计算以存储结果时得到的结果。
另一方面,它起作用:

This doesn't work as I expected, and the result of a / b is always that which I would get if I performed the calculation using an int to store the results. On the other hand, this works:

double calculate1 = a;
double calculate2 = b;
double texturefactor = ((calculate1 / calculate2) * 10);

也许是愚蠢的问题-
1.我确定这应该有效-我知道在某些情况下VS会抱怨我试图将一种类型隐式转换为另一种-这就是我要尝试的方法!为什么不呢,我错过了什么吗? :)
2.我应该只将计数器a和b转换为双精度并为自己省去转换的麻烦吗?还是

Couple of perhaps stupid questions- 1. I'm sure this ought to work- I know that in certain situations VS will complain that I've tried to implicitly convert from one type to another- That's what I'm trying to do! Why doesn't it, and have I missed something? :) 2. Should I just convert the counters a and b to doubles and save myself the trouble of the conversion, or is that trouble?

推荐答案

从内部到外部对表达式(包括子表达式的类型)进行求值:

The expression, including the types of subexpressions, is evaluated from inside to outside:

double texturefactor = ((a / b) * 10);

当编译器分析 a / b 时,它不知道结果以后会转换为 double ,因此它只是将计算编译为整数除法。

When the compiler analyses a / b, it has no idea that the result will later on be converted to double, so it just compiles the computation as an integer division.

显式地将两个操作数之一强制转换为 double ,足以避免这种混乱:

Explicitly casting one of the two operands to double right there is enough to avoid that confusion:

double texturefactor = (((double)a / b) * 10);

这篇关于将int隐式转换为double的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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