-2
我在 https://projecteuler.net/problem=8(從1000個字符串中查找最高的13個連續數字的產品)任務中遇到某種問題,某些點程序給了我可預測的結果,然後該函數返回一個非常接近於無符號long long int範圍內的數字。它發生的地點取決於所讀取的值,例如,如果數字串主要由8和9組成,那麼它會比只有5和6秒的情況更早發生。爲什麼會發生?項目歐拉任務#8,代碼在某個點後開始回答錯誤的答案
#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;
}
程序打印出目前最高的產品,目前所有的數字包含在數組中。 它看起來像這樣: The error