欧拉项目任务#8,代码在某个点之后开始返回错误的答案
Project Euler task #8, code starts returning wrong answers after certain point
我在一项任务中遇到了某种问题 https://projecteuler.net/problem=8,(从 1000 个数字字符串中查找 13 个连续数字的最高乘积),其中程序在某种程度上给了我可预测的结果,然后函数返回一个非常接近无符号长整形范围的数字。它发生的点取决于读取的值,例如,如果数字字符串主要由 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;
}
程序打印出当前最高的乘积和数组中当前包含的所有数字。它看起来像这样:错误
使用 unsigned long long int
而不是 int 来计算乘积。13 位数字的乘积很容易变得大于最大的 int。
相关文章:
- 当回溯以零开始时,如何调试崩溃
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 在类定义之后定义一个私有方法
- 在循环C++中指定字符串之后,不会打印该字符串
- C++宏忽略之后的内容
- 要与"if constexpr"一起使用的编译时消息(在预处理器之后)
- 根据用户输入用字母填充矢量,并将"开始"和"结束"放在四肢
- strncpy之后的char数组的错误行为
- 计算十进制 c++ 之后的数字
- 如何从头开始创建 avi 文件?
- 为什么 -mmacosx-version-min=10.10 不阻止使用标记为从 10.11 开始的函数?
- 自一周开始以来的秒数?
- "x += x--"之后的 x 是什么?
- 类的前向声明之后的类成员函数定义,在类声明之前
- 为什么将双精度转换为 int 似乎在第 16 位数字之后将其四舍五入?
- 一旦双簧管录制开始,主 UI 线程就会被阻止
- 在我关闭刚开始的孩子对话框并进入父母对话框之后,我的QT桌面应用程序不断崩溃
- 返回从字符串末尾 (C++) 之后的位置开始的子字符串
- 欧拉项目任务#8,代码在某个点之后开始返回错误的答案
- 如何在c++中从endl之后开始打印