c++整数乘以整数溢出
作者:野牛程序员:2024-04-06 17:44:44 C++阅读 2928
c++整数乘以整数溢出
C++中,当两个整数相乘的结果超出了该整数类型的表示范围时,就会发生整数溢出。这可能导致结果不正确或未定义的行为。要避免这种情况,可以使用更大的整数类型(如long long
)来存储结果,或者在计算之前检查是否会发生溢出。
//原因:
//对于编译器来说,int和int相乘,结果也是先存在int中,跟被赋给long还是long long数据类型的字段没有关系。
//解决办法:
// 要不溢出,就要把两个32位数强制转换成long或long long类型,再相乘。
#include <iostream> using namespace std; int main(){ cout<<"999999 * 999999 :"<<999999 * 999999<<endl; int a=999999 * 999999; cout<<"int a=999999 * 999999 :"<<a<<endl; long b=999999 * 999999; cout<<"long b=999999 * 999999 :"<<b<<endl; long c=long(999999)* 999999; cout<<"long c=long(999999)* 999999 :"<<c<<endl; long d=long(999999)* long(999999); cout<<"long d=long(999999)* long(999999) :"<<d<<endl; long long e=999999 * 999999; cout<<"long long e=999999 * 999999 :"<<e<<endl; long long f=(long long)999999 * 999999; cout<<"long long f=(long long)999999 * 999999 :"<<f<<endl; long long g=(long long)(999999 )* (long long)(999999); cout<<"long long g=(long long)(999999 )* (long long)(999999) :"<<g<<endl; long long h = 999999LL * 999999LL; cout<<"long long h = 999999LL * 999999LL :"<<h<<endl; return 0; }
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892