C++中两个整数的乘法 [英] Multiplication of two integers in C++

查看:37
本文介绍了C++中两个整数的乘法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常基本的问题,但我不确定我是否理解这个概念.假设我们有:

I have a pretty basic question, but I am not sure if I understand the concept or not. Suppose we have:

int a = 1000000;
int b = 1000000;
long long c = a * b;

当我运行它时,c 显示负值,所以我也将 ab 更改为 long long 然后一切都很好.那么为什么我必须更改 ab,当它们的值在 int 范围内并且它们的产品分配给 c(即long long)?

When I run this, c shows negative value, so I changed also a and b to long long and then everything was fine. So why do I have to change a and b, when their values are in range of int and their product is assigned to c (which is long long)?

我正在使用 C/C++

I am using C/C++

推荐答案

int在乘法之前没有提升为long long,它们仍然是ints 和产品也是如此.然后将产品转换为 long long,但为时已晚,溢出发生了.

The ints are not promoted to long long before multiplication, they remain ints and the product as well. Then the product is cast to long long, but too late, overflow has struck.

拥有 ab long long 中的一个应该也可以工作,因为另一个会被提升.

Having one of a or b long long should work as well, as the other would be promoted.

这篇关于C++中两个整数的乘法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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