为什么以下代码没有给出所需的答案?
昨天在一次采访中,面试官问了我一个问题:
为什么下面的代码没有给出想要的答案?
int a = 100000, b = 100000;
long int c = a * b ;
语言是 C。
我告诉面试官,我们首先将 100,000 * 100,000 算作 int(溢出),然后将其转换为 long。
Yesterday on an interview the interviewer asked me a question:
Why doesn't the following code give the desired answer?
int a = 100000, b = 100000;
long int c = a * b ;
The language is C.
I've told the interviewer that we count first the 100,000 * 100,000 as an int(overflow) and just then cast it to long.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我猜测线索将是发生整数溢出,但由于值如此之低,我没有看到这种情况发生。
int(通常为 32 位)的最大(正)值为:2,147,483,647
计算结果为:100,000,000
更新:
更新后的问题:
100000 * 100000< /code> 而不是
10000 * 10000
会导致 10,000,000,000,这将导致发生溢出。然后将该值转换为 long。为了防止这种溢出,正确的方法是将乘法中的两个值之一转换为 long(通常是 64 位)。例如
(长)100000 * 100000
I'm guessing the clue would be an integer overflow to occur, but with such low values, I don't see that happening.
Maximum (positive) value for int (usually 32bit) is: 2,147,483,647
The result of your calculation is: 100,000,000
UPDATE:
With your updated question:
100000 * 100000
instead of10000 * 10000
results in 10,000,000,000, which will cause an overflow to occur. This value is then cast to a long afterwards.To prevent such an overflow the correct approach would be to cast one of the two values in the multiplication to a long (usually 64bit). E.g.
(long)100000 * 100000
这是因为它首先将其计算为 int,然后才将其转换为 long 变量。(因此它首先作为整数溢出,然后变成 long)
代码应该是
That's cause it first calculates it as an int, and only then casts it into a long variable.(so it first overflows as an integer and then becomes a long)
the code should be
100000*100000
是10000000000
(10,000,000,000
),它大于 32 位int
可以表示的最大值 (< code>2,147,483,647),因此它溢出。a*b
仍然是int
,它不是long int
,因为表达式a*b
的成员都是int
类型,因此它们不会转换为long int
:此转换仅在a*b
求值后才会发生,当结果被分配给c
时。如果您希望a*b
的结果为long int
,则需要将至少一个操作数转换为long int
:此外< code>long int 可以与
int
具有相同的大小(也可以用 32 位表示):这最有可能发生在 32 位应用程序中,通常,sizeof(int) == sizeof(long int) == 4
。如果您需要
c
为 64 位,您最好使用像 这样的变量int64_t
,确保您是 64 位的。100000*100000
is10000000000
(10,000,000,000
) which is greater than the maximum value a 32bitint
can represent (2,147,483,647
), thus it overflows.a*b
is still anint
, it's not along int
, since the members of expressiona*b
are both of typeint
, thus they aren't converted tolong int
: this conversion will only happen aftera*b
has been evaluated, when the result is assignedc
. If you want the result ofa*b
to belong int
you need to convert at least one of the operands aslong int
:Moreover
long int
could be of the same size ofint
(it could be represented on 32 bits too): this is most likely to happen with 32 bit application where, usually,sizeof(int) == sizeof(long int) == 4
.If you need
c
to be of 64 bits you should better use a variable likeint64_t
, that ensures you to be of 64 bits.