-2

https://projecteuler.net/problem=8のタスクで何らかの問題が発生しています (1000 の数字の文字列から 13 の連続した数字の最高の積を見つける)。ある時点まで、プログラムは予測可能な結果を​​もたらします。そして、関数はunsigned long long intの範囲に非常に近い数値を返します。それが発生するポイントは、読み取られた値によって異なります。たとえば、数字の文字列がほとんど 8 と 9 で構成されている場合、5 と 6 のみの場合よりも早く発生します。なぜそれが起こるのですか?

#include <iostream>
#include <fstream>

using namespace std;


int product (int res, int a, char buffer[]){
for (int i = 0; i < a; i++){
//simple char to int conversion
res*=(buffer[i] - '0');
}

return res;
}

int main () {
char check;
int res = 1;
fstream plik;
plik.open ("8.txt");
unsigned long long int high;
unsigned long long int result;
//main function in the program
if (plik.good()){
    char buffer [13];
    for (int i = 0; i < 13; i++){
        plik >> buffer[i];
    }
    result = product (res, 13, buffer);
    high = result;
    cout << high << endl;
    //the main checking loop
    while (!plik.eof()){
    //just an interruption to make it possible to view consecutive products
    //the iteration in the buffer
    for (int i = 0; i < 12; i++){
    buffer[i] = buffer[i+1];
    }
    plik >> buffer[12];
    result = product (res, 13, buffer);
    //comparison between the current product and highest one
    if (high < result){
    high = result;
    }
    cin >> check;
    cout << high << endl;
    //again a tool for checking where the problem arises
    for (int i = 0; i < 13; i++){
        cout << buffer[i] << "  ";
    }
    cout << endl;
    }
    plik.close();
    cout << high << endl;
}

return 0;

}

プログラムは、現在最も高い積と、配列に現在含まれているすべての数値を出力します。次のようになります 。エラー

4

1 に答える 1

1

unsigned long long int積を計算するには、int の代わりに使用します。13 桁の積は、最大の int よりも簡単に大きくなる可能性があります。

于 2016-02-17T18:53:17.070 に答える