C++ Project Euler任务#8,代码在某一点后开始返回错误答案
我在一项来自的任务中遇到了一些问题 ,(从1000个数字字符串中查找13个连续数字的最高乘积),其中程序在某种程度上给出可预测的结果,然后函数返回一个非常接近无符号长整型范围的数字。它出现的点取决于读取的值,例如,如果数字串主要由8s和9s组成,则它会比只有5s和6s的情况发生得更快。为什么会这样C++ Project Euler任务#8,代码在某一点后开始返回错误答案,c++,debugging,overflow,codeblocks,unsigned-long-long-int,C++,Debugging,Overflow,Codeblocks,Unsigned Long Long Int,我在一项来自的任务中遇到了一些问题 ,(从1000个数字字符串中查找13个连续数字的最高乘积),其中程序在某种程度上给出可预测的结果,然后函数返回一个非常接近无符号长整型范围的数字。它出现的点取决于读取的值,例如,如果数字串主要由8s和9s组成,则它会比只有5s和6s的情况发生得更快。为什么会这样 #include <iostream> #include <fstream> using namespace std; int product (int res, int
#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;
}
#包括
#包括
使用名称空间std;
int-product(int-res、int-a、字符缓冲区[]){
for(int i=0;i>缓冲区[i];
}
结果=产品(res,13,缓冲液);
高=结果;
cout缓冲器[12];
结果=产品(res,13,缓冲液);
//当前产品与最高产品的比较
如果(高<结果){
高=结果;
}
cin>>检查;
cout使用无符号长整型
代替整型来计算乘积。13位的乘积很容易大于最大整型