c# - 将 int 转换为 int64,int 变量仍然在 int.MaxValue 处返回负数

标签 c#

我正在尝试显示商品的价格。价格乘以商品数量。

int itemCost = itemPrice * itemQuanity;

当元素数量过多时,itemCost 变为负数,这意味着我需要一个更大的 int,所以我将 int 更改为使用 int64。

int64 itemCost = itemPrice * itemQuantity;

有了这个改变,它仍然输出一个负的 itemCost,我做错了什么?

我试过用

System.Convert.ToInt64(int value);

但这似乎也不起作用,在达到 int.MaxValue 时仍然得到负数。

最佳答案

itemPrice 是什么类型和 itemQuantity ?如果它们都是 int ,你会得到一个 int (32 位)作为乘法的答案,然后将其存储在 int64 中.那时,转换(和溢出)已经发生,并转换为 int64。不会有帮助的。

在相乘之前,您需要确保两个操作数都是 int64 。所以如果他们还没有,

int64 itemCost = ((int64) itemPrice) * ((int64) itemQuantity);

关于c# - 将 int 转换为 int64,int 变量仍然在 int.MaxValue 处返回负数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15095190/

相关文章:

c# - 如何从不活动但与事件服务器连接的服务器设置 Img src

c# - 在 C#2008 asp.net 页面上动态添加文本字段

c# - 使用无限 while 循环处理客户端/服务器数据的最佳实践

c# - 当你在不使用 new 关键字的情况下创建结构时会发生什么?

c# - Marshal.SizeOf(Type t) 函数

c# - DataGrid 复制到带有样式的剪贴板

c# - 更改默认 View 引擎的 View 搜索行为

c# - 不可发音成员 ''不能像方法一样使用

c# - 文本框中所选 dataGridView 单元格的值

c# - 带有可见可点击控件的透明表单