gpt4 book ai didi

c - 错误项目 Euler #8

转载 作者:太空宇宙 更新时间:2023-11-04 05:56:43 26 4
gpt4 key购买 nike

我正在研究 Problem 8 of Project Euler我必须从给定的 1000 位数字中找到 13 个连续数字的最大乘积。我将该数字存储在一个文本文件中,然后将其输入到我的源代码中。我的代码编译并运行,但我的回答似乎不正确。谁能帮我找出错误所在?

这是我的代码:

#include <stdio.h>
int main()
{
int x,ar[1000],i = 0,prod = 0,tmp=1;
FILE* fp = fopen("file.txt","r");
if (fp == NULL)
{
printf("error");
return 1;
}
while((x = fgetc(fp)) != EOF)
{
ar[i] = x;
i++;
}
/*for(int m =0;m<999;m++)
{
printf("%d",ar[m]);
}*/
for(int j =0;j <= 986;j++)
{
for(int k=j;k<j+13;k++)
{
tmp = tmp * ar[k];
}
if(tmp > prod)
{
prod = tmp;
}
}
printf("%i",prod);
return 0;
}

最佳答案

13 位连续数字的乘积可能超出您用于 tmpint 范围。您需要支持更广泛范围的数据类型。也许像 unsigned long long 这样的 64 位的就可以了。

另外正如@deviantfan 所指出的,您正在读取字符,'0' 作为字符与数字 0 不同。阅读有关 ASCII 的信息。

另一个问题是 tmp 的逻辑不正确:你没有在每 13 步循环后将它重新初始化为 1

编辑:

回复您的评论:我想在这种情况下最好的解决方案是将数据读取为字符,但是之后您可以将 ASCII 转换为整数,例如:

while((x = fgetc(fp)) != EOF)
{
// x - '0' does the conversion,
// e.g. the expression obtains 0 from '0' - '0', and 5 from '5' - '0'
ar[i] = x - '0';
i++;
}

关于c - 错误项目 Euler #8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26240690/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com