-2

我在https://projecteuler.net/problem=8的任务中遇到了某种问题 (从 1000 个数字字符串中找到 13 个连续数字的最高乘积),直到某个时候,程序给了我可预测的结果然后该函数返回一个非常接近unsigned long long int范围的数字。它发生的点取决于读取的值,例如,如果数字串主要由 8s 和 9s 组成,那么它会比只有 5s 和 6s 更快地发生。为什么会这样?

#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 回答