Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

c# - Implicitly converting int to double

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).

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

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The result of a / b is another integer, so even if you do this, the damage has already been done:

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

Try casting one of your inner variables to a double:

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

The result of (double)a / b will be a double, and you won't lose your fraction.

To answer your second question:

Should I just convert the counters a and b to doubles

That'd work too. If you change those to double, then you wouldn't have to perform the above cast.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...