我编写了以下代码,用于查找通过两个 3 位数字的乘积获得的第一个回文数:
#include <stdio.h>
int main()
{
int pro,d,sum=0,c;
for (int a=100;a<1000;a++)
{
for (int b=a;b<1000;b++)
{
pro=a*b;
d=pro;
while (d!=0)
{
c=d%10;
sum= sum*10 + c;
d=d/10;
}
if (sum==pro)
{
printf("%d is a palindrome \n",sum);
return 0;
}
}
}
return 0;
}
但是当我运行代码时它没有给我任何输出。 有什么帮助吗?
最佳答案
您需要在每次迭代或内部 for 循环后重置总和值,否则它将在下一个后续迭代中使用前一个迭代值。
代码:
#include <stdio.h>
int main()
{
int pro,d,sum=0,c;
for (int a=100;a<1000;a++)
{
for (int b=a;b<1000;b++)
{
pro=a*b;
d=pro;
while (d!=0)
{
c=d%10;
sum= sum*10 + c;
d=d/10;
}
if (sum==pro)
{
printf("%d is a palindrome \n",sum);
return 0;
}
sum=0;
}
}
return 0;
}
输出:
10201 is a palindrome
关于c - 两个 3 位数字的乘积是回文数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52462386/