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++中两个整数的乘法
- 近似搜索的工作原理 2021-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 从python回调到c++的选项 2022-11-16
- C++ 协变模板 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 静态初始化顺序失败 2022-01-01
