将int与长结果相乘C# [英] Multiplying int with long result c#

查看:209
本文介绍了将int与长结果相乘C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想知道为什么. C#.Net 3.5

Wonder why. C# .Net 3.5

int a = 256 * 1024 * 1024;
int b = 8;
long c = b * a;
Console.WriteLine(c);//<-- result is -2147483648 

这是哪里减去的?

推荐答案

这是哪里减去的?

Where does this minus from?

从整数溢出.请注意,您的代码等效于:

From the integer overflow. Note that your code is equivalent to:

int a = 256 * 1024 * 1024;
int b = 8;
int tmp = b * a;
long c = tmp;
Console.WriteLine(c);

我将乘法与赋值给long的变量分开,以强调它们确实是独立的运算-乘法是使用Int32算术执行的,因为两个操作数均为Int32-然后将结果分配给Int64无关.

I've separated out the multiplication from the assignment to the long variable to emphasize that they really are separate operations - the multiplication is performed using Int32 arithmetic, because both operands are Int32 - the fact that the result is assigned to an Int64 afterwards is irrelevant.

如果要以64位算术执行乘法,则应将其中一个操作数强制转换为long(即Int64):

If you want to perform the multiplication in 64-bit arithmetic, you should cast one of the operands to long (i.e. Int64):

int a = 256 * 1024 * 1024;
int b = 8;
long c = b * (long) a;
Console.WriteLine(c); // 2147483648

(强制转换为long的操作数并不重要-另一个操作数将隐式转换为long.)

(It doesn't matter which operand you cast to long - the other one will be implicitly converted to long anyway.)

这篇关于将int与长结果相乘C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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