![](/img/trans.png)
[英]if statement not evaluating to false? Program giving strange output. Why?
[英]if i am taking A = 10^9 and B=10^9 than following code is giving negative output. why? It is giving me correct output for small integers
A 和 B 是從 1 到 10^9 的整數,pairs 是一個包含表達式值的變量 ((A/2) (B/2)+((A-(A/2)) (B-(B /2))))
#include<iostream>
using namespace std;
int main()
{
int T;
cin>>T;
while(T--)
{
long int A,B;
cin>>A>>B;
//cout<<A<<" "<<B<<endl;
long long int pairs = ((A/2)*(B/2)+((A-(A/2))*(B-(B/2))));
cout<<pairs<<"\n";
}
return 0;
}
在許多實現中,C++ 中的long int
只是一個 32 位數字,最大值為 2,147,483,647。 所以如果 A 是 10^9 而 b 也是 10^9,它們的乘積超過了 32 位數字的最大值(實際上 A 和 B 可以遠小於 10^9,所以它們的乘積超過 21.5 億) . 因此產品溢出。 正如評論中所建議的,
您可以將 A 和 B 的定義更改為long long int
#include<iostream>
using namespace std;
int main()
{
int T;
cin>>T;
while(T--)
{
long long int A,B; // here
cin>>A>>B;
//cout<<A<<" "<<B<<endl;
long long int pairs = ((A/2)*(B/2)+((A-(A/2))*(B-(B/2))));
cout<<pairs<<"\n";
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.