#include<iostream>
using namespace std;
int a;
int b;
int main()
{
cin >> a >> b;
if(a >= b)
{
if((a - b) % 2 == 1) cout << (a - b + 1) / 2 << endl;
else if(a % 2 == 0 && b % 2 == 0) cout << (a - b) / 2 + 1 << endl;
else cout << (a - b) / 2 << endl;
}
if(b > a)
{
if((b - a) % 2 == 1) cout << (b - a + 1) / 2 << endl;
else if(a % 2 == 0 && b % 2 == 0) cout << (b - a) / 2 + 1 << endl;
else cout << (b - a) / 2 << endl;
}
return 0;
}
為什麼打0和2147483647時會出現 -1073741824???
#include
using namespace std;
int a;
int b;
int main()
{
cin >> a >> b;
if(a >= b)
{
if((a - b) % 2 == 1) cout << (a - b + 1) / 2 << endl;
else if(a % 2 == 0 && b % 2 == 0) cout << (a - b) / 2 + 1 << endl;
else cout << (a - b) / 2 << endl;
}
if(b > a)
{
if((b - a) % 2 == 1) cout << (b - a + 1) / 2 << endl;
else if(a % 2 == 0 && b % 2 == 0) cout << (b - a) / 2 + 1 << endl;
else cout << (b - a) / 2 << endl;
}
return 0;
}
為什麼打0和2147483647時會出現 -1073741824???
其實你應該有發現測資全是正數(而且a必小於b)
所以判斷a,b大小的條件式可以省去
其實2147483647這數字相當危險(踩在int的邊界)
建議你可以用unsigned int 宣告你的變數