加倍一个数字 - 左移与乘法 [英] Doubling a number - shift left vs. multiplication

查看:198
本文介绍了加倍一个数字 - 左移与乘法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是

int size = (int)((length * 200L) / 100L); // (1)

int size = length << 1; // (2)

(长度为int在两种情况下)

(length is int in both cases)

我认为这两个code段要长参数翻一番。

I assume both code snippets want to double the length parameter.

我会尝试使用(2)......那么,有没有什么优势,使用(1)?我看了看,当溢出发生边缘情况,并且两个版本似乎有相同的行为。

I'd be tempted to use (2) ... so are there any advantages for using (1)? I looked at the edge cases when overflow occurs, and both versions seem to have the same behavior.

请告诉我,我缺少什么。

Please tell me what am I missing.

推荐答案

这里是第三个选项:

int size = length * 2; // Comment explaining what is 2 or what means this multiplication

这一定是最好的选择。由于它是可读的,容易理解你想要做什么。 至于性能,编译器生成pretty的优化code,所以没有必要担心这样一个简单的操作。 如果您有关于溢出的任何问题,你可以使用检查块。

And this must be the best option. As it is readable and easy to understand what you want to do. As for performance, compilers are generating pretty optimized code, so no need to worry for such a simple operation. If you have any concerns concerning overflow you can use checked block.

修改正如许多其他人只是使用任何有意义的变量,而不是 2 在这里。

EDIT As mentioned by many others just use any meaningful variable instead of 2 here.

这篇关于加倍一个数字 - 左移与乘法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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