請用遞迴寫回文(要用c語言)

2009-04-03 7:20 am
A numeric palindrome is a number that is the same when read either forward or backward. For example, the number 4321234 is a numeric palindrome. Write a recursive function named numpal() that accepts an integer number as a parameter and returns a 1 if the parameter is a numeric palindrome and a 0 if it is not.
Enter a number:
12345
12345 is not a numeric palindrome
Enter a number:
543212345
543212345 is a numeric palindrome
更新1:

希望可以用到第七章以前的 拜託

回答 (2)

2009-04-03 10:59 am
✔ 最佳答案
#include <stdio.h>
#include <stdlib.h>

char str[256]="";

int numpal(int begin, int end)
{
if ( begin == end ) {
return 1;
} else if ((end - begin) == 1) {
return (*(str + begin) == *(str + end));
} else if (*(str + begin) == *(str + end)) {
return numpal(++begin,--end);
} else {
return 0;
}
}

int main()
{
int i, done;

printf("Check program for numeric palindrome.\n");
printf("Please enter a number to be checked or a negative number to end.\n");

done = 0;
while (!done) {
printf("Enter a number\n");
scanf("%s", str);
i = atoi(str);
if (i < 0) {
done = 1;
} else {
if (numpal(0, strlen(str)-1)) {
printf("%s is a numeric palindrome\n", str);
} else {
printf("%s is not a numeric palindrome\n", str);
}
}
}
return 0;
}
2009-04-05 4:28 am
...... Write a recursive function named numpal() that accepts an integer number as a parameter ......

首先,題目明定遞迴函式僅接收一個整數引數,回答001的遞迴式明顯與題意不合!

另又借用「全域」字元陣列,令遞迴式欠缺「完整性」,此其二也。

再者,在呼叫前須先把該數轉成字串,再用字元指標來比對字元,已與 numeric 大異其趣,此其三也。


收錄日期: 2021-04-29 22:18:09
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20090402000010KK10800

檢視 Wayback Machine 備份