Multiplication of two integers in C++(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 显示负值,所以我也将 a 和 b 更改为 long long 然后一切都很好.那么为什么我必须更改 a 和 b,当它们的值在 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.
拥有 a 或 b long long 中的一个应该也可以工作,因为另一个会被提升.
Having one of a or b long long should work as well, as the other would be promoted.
这篇关于C++中两个整数的乘法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++中两个整数的乘法
基础教程推荐
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- CString 到 char* 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
