我正在练习递归,但我对问题的解决方案似乎不起作用。 我正在尝试编写一个递归代码来确定数字的数字是否按升序排列。这是我的代码:
#include <stdio.h>
int isAscending(int num);
int main(){
int result;
result = isAscending(123);//Should print "The number is in ascending order!"
if (result == 0) {
printf("The number is in ascending order!\n");
}
else {
printf("The number is not in ascending order!\n");
}
}
int isAscending(int num) {
int new = num / 10;
int result = 0;
if ((num % 10) == 0) {
return 0;
}
else if ((num % 10) > (new % 10)) {
result += isAscending(num / 10);
return result;
}
else {
return 1;
}
}
最佳答案
这是另一种(简单的)方法。基本思想是,如果我们有一个数字,我们返回肯定,否则我们检查最右边的数字是否大于它左边的数字。我们对剩余的数字执行此操作。
#include <stdio.h>
int isAsc(int i)
{
int rem = i % 10; // remainder
int quo = i / 10; // quotient
if (rem == i)
return 1;
else if (rem <= (quo % 10))
return 0;
else
return 1 && isAsc(quo);
}
int main(void)
{
int i = 123123;
if (isAsc(i))
printf("%s\n", "Ascending");
else
printf("%s\n", "Not ascending");
return 0;
}
关于c - 一个递归函数,判断一个数的数字是否按升序排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46283897/