我必须找到下面一个 1000 位数字的 13 个相邻数字的最大乘积。我的问题代码如下:
#include <stdio.h>
int main()
{
char arr[1000] =
"731671765313306249192251196744265747423553491949349698352031277450"
"632623957831801698480186947885184385861560789112949495459501737958"
"331952853208805511125406987471585238630507156932909632952274430435"
"576689664895044524452316173185640309871112172238311362229893423380"
"308135336276614282806444486645238749303589072962904915604407723907"
"138105158593079608667017242712188399879790879227492190169972088809"
"377665727333001053367881220235421809751254540594752243525849077116"
"705560136048395864467063244157221553975369781797784617406495514929"
"086256932197846862248283972241375657056057490261407972968652414535"
"100474821663704844031998900088952434506585412275886668811642717147"
"992444292823086346567481391912316282458617866458359124566529476545"
"682848912883142607690042242190226710556263211111093705442175069416"
"589604080719840385096245544436298123098787992724428490918884580156"
"166097919133875499200524063689912560717606058861164671094050775410"
"022569831552000559357297257163626956188267042825248360082325753042"
"0752963450";
int i, j;
long int max;
max = 0;
long int s = 1;
for (i = 0; i < 988; i++) {
int a = 0;
for (j = 1; j <= 13; j++) {
printf("%c", arr[i + a]);
s = s * arr[i + a];
a++;
}
printf("%c%d", '=', s);
printf("\n");
if (s > max) {
max = s;
}
}
printf("\nMaximum product is %d", max);
getchar();
}
即使没有输入为零,某些输出也为零。第二个输出恰好为负。答案甚至不匹配。如有任何帮助,我们将不胜感激。
最佳答案
char
数组 arr
中的许多 13 位数字集合包含零,这就是为什么这些集合相乘的结果将是 0。
您的代码存在几个问题:
- 您正在使用
%d
而不是%ld
来打印long int
。使用错误的转换说明符将导致未定义的行为。
If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.
- 在乘法之前,您并未将数字的 ASCII 值转换为其实际值。 (“0”的 ASCII 值为 48)。这会导致整数溢出,并且是打印负值的原因。
所以声明:
s = s * arr[i + a];
应更改为:
s = s * (arr[i + a] - '0');
- 您也没有在内部
for
循环开始时将乘积s
重置为 1,因此,您最终会将不同结果的值相乘13 套。
进行这些更改后,您可以看到现场演示 here .
关于c - 1000 位数字的 13 个相邻数字的最大乘积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53440887/