我在任务中遇到某种问题 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;
}
该程序打印出当前最高的产品和当前包含在阵列中的所有数字。 它看起来像这样: The error
答案 0 :(得分:1)
使用unsigned long long int
代替int来计算产品。 13位数的乘积很容易变得大于最大的int。