我只是想在 C 中使用递归来找到回文数。但是我犯了一个错误,而且我不知道这个错误。每次它给我的结果都是 0。
这是源代码:
<小时/>#include<stdio.h>
#include<conio.h>
int pal(int num);
void main()
{
int num=625,res=0;
res=pal(num);
printf("%d",res);
getch();
}
int pal(int num)
{
int ans=0,rem=0,index=0;
index=log10(num);
if(index==0)
{
return ;
}
index--;
rem=num%10;
ans=ans*10+rem;
return pal(index--);
}
请给我最简单的找到它的方法。我需要一个易于理解的程序。
最佳答案
一些问题:
- 您正在使用
index
而不是num
递归调用pal
; - 如果
index
为 0,您需要返回一个值 - 该值应该是什么? main
返回int
,而不是void
;- 您对代码要执行的操作的描述不清楚 - 您是否试图反转一个数字,确定它是否是回文,什么?
假设您尝试反转一个数字,递归算法将类似于:
int reverse( int num )
{
/**
* Account for negative inputs by preserving the sign and
* converting the input to positive for processing.
*/
int sign = 1;
if ( num < 0 )
{
sign = -1;
num = -num;
}
/**
* If the input is a single digit, then there's
* nothing to reverse and we return the original
* input value.
*/
if ( num < 10 )
return sign * num;
/**
* Otherwise, find and preserve the least significant digit.
*/
int remainder = num % 10;
/**
* Recursively call reverse on the higher-order digits.
*/
int rev = reverse( num / 10 );
/**
* Determine the order of magnitude of the reversed
* value, multiply the remainder by that magnitude
* to make it the new most significant digit.
*/
for ( int tmp = rev; tmp; tmp /= 10 )
remainder *= 10;
/**
* PARENTHESES MATTER HERE
*/
return sign * (remainder + rev);
}
编辑
我添加了一些文档,希望能让代码更加清晰。我还更改了余数相乘的方式,因此它不依赖于 pow 函数。
关于c - C中使用递归的回文数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52742014/