簡體   English   中英

如果我采用 A = 10 ^ 9 和 B = 10 ^ 9,則以下代碼給出負 output。 為什么? 對於小整數,它給了我正確的 output

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM