Hey, I am working on a school project and a line of code I just wrote kind of made me l开发者_运维技巧augh and think to myself, "There must be a better way to do what I just did". So, my question is, is this really the best way to do this? It seems kind of silly. BTW, size is an int that is passed to this function.
int tiles = Convert.ToInt32(Math.Sqrt(Convert.ToDouble(size)));
I know this works, but is there a better way?
Since int
is implicitly convertable to double, you can leave out the inner conversion:
int tiles = Convert.ToInt32(Math.Sqrt(size));
That being said, Convert.ToInt32
is overkill in this situation. You can also just use a simple cast, since you know it's going from double
to int
:
int tiles = (int)Math.Sqrt(size);
精彩评论