算法总结(1)--十题一章(未完)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36427244/article/details/83004966

四则运算溢出判断

加法思路:两负数相加溢出值为正,两正数相加溢出值为负.
加法例题:
给定区间[-2的31次方, 2的31次方]内的3个整数A、B和C,请判断A+B是否大于C。
本题关键变在于溢出处理,核心部分:
如果a+b>c && c-b<a,那么a+b一定大于c
如果a+b<c && a+b<0,那么a+b一定大于c
代码实例(c++):

#include<iostream>
using namespace std;
int main()
{
int p;
    int test[10][3]={0};
    cin>>p;
    for(int i=0;i<p;i++)
    {
        for(int t=0;t<3;t++)
        {
            cin>>test[i][t];
        }
    }
    for(int s=0;s<p;s++)
    {
        if((int)(test[s][0]+test[s][1])>test[s][2] &&test[s][2]-test[s][1]<test[s][0])
        {
            cout<<"Case #"<<s+1<<": true"<<endl;
        }
		else if((int)(test[s][0]+test[s][1])<0)
		{
		cout<<"Case #"<<s+1<<": true"<<endl;
		}
        else{
            cout<<"Case #"<<s+1<<": false"<<endl;
        }
    }
return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_36427244/article/details/83004966