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

查看:34
本文介绍了将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?

推荐答案

这个减号是从哪里来的?

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天全站免登陆