长整数超出范围负积

问题描述 投票:0回答:1

我试图找到一些长整型的乘积(0<=a[i]<=10^18)t. now how do i find that the product exeeds 10^18? does the product turn into negetive number (product<0)?

#include<bits/stdc++.h>
using namespace std;
int main(){
    int n;
    cin>>n;
    long long a[n],product=1;
    for(int i=0;i<n;i++){
        cin>>a[i];
    }
    sort(a,a+n);
    for(auto i:a){
        product*=i;
        if(i==0) break;
        if(product>1000000000000000000) {
            cout<<-1;
            return 0;
        }
    }
    cout<<product;
}
c++ long-integer long-long
1个回答
0
投票

我对您的代码进行了一些更改,以获得更好的 C++ 编码习惯和约定。我通过评论解释了原因。

对于这段代码,它会检查输入的数字是否为负数,因为你提到了

integer (0<=a[i]<=10^18)
,并且当产量超过10^18时,它会显示信息。希望您觉得它有用!

#include <algorithm> // for std::sort
#include <iostream>  // for std::cin, std::cout, std::endl

int main()
{
    int n;
    std::cin >> n;
    long long a[n], product = 1;

    for (int i = 0; i < n; i++)
    {
        long long val;
        std::cin >> val;

        if (val < 0) // Since you mentioned that integer is between 0 and 10^18.
        {
            std::cout << "Negative number is not allowed! Please re-enter!" << std::endl;
            i -= 1; // The negative number will not be counted in.
        }
        else
        {
            a[i] = val;
        }
    }

    std::sort(a, a + n);
    for (const int i : a) // Since int is very short, auto is not necessary here. Just use int for readability.
    // The const will tell people that i will not be modified during the loop, also for readability.
    {
        product *= i;

        if (i == 0)
        {
            break;
        }

        if (product > 1e18) // C++ allows scientific notation.
        {
            std::cout << "The product has exceeded 1e18!" << std::endl; // Easier to understand than just print -1.
            return 0;
        }
    }

    std::cout << "The product is " << product << std::endl;

    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.