简体   繁体   English

C中的递归函数返回给定数字右侧的第n位数字

[英]Recursive function in C that returns the nth digit from the right of a given number

The function int digit(int number,int position) has to be recursive and return the digit of "number" in the position "position" from the right.函数int digit(int number,int position)必须是递归的,并从右侧的“position”位置返回“number”的数字。 So in my code where number=5864 and position=3 the function should return "8".所以在我的代码中, number=5864 和 position=3 函数应该返回“8”。 Here's the main code.这是主要代码。

#include <stdio.h>

int digit(int number,int position);

 int main (){
int number=5864, position=3, result;
result=digit(number,position);
printf("result: %d\n",result );
system("pause");

return 0;
}

int digit(int number,int position){}

I know that this question has already been asked but I'm really struggling to make it recursive.我知道已经有人问过这个问题,但我真的很难让它递归。 Thanks for your attention.感谢您的关注。

For a recursion definition, you need two things - a rule on how to move the recursion on, and a rule on how to stop the recursion.对于递归定义,您需要两件事——关于如何继续递归的规则,以及关于如何停止递归的规则。 For this usecase, you can formalize these rules as follows:对于此用例,您可以将这些规则形式化如下:

  • If position == 1, return the rightmost digit如果position == 1,则返回最右边的数字
  • If position > 1, divide number by 10 and decrement position如果position > 1,则将number除以 10 并递减位置

Or, in C code:或者,在 C 代码中:

int digit(int number, int position) {
    if (position == 1) {
        return number % 10;
    }
    return digit(number / 10, --position);
}

Note: This code is a bit simplistic, and doesn't handle invalid inputs.注意:此代码有点简单,不处理无效输入。 A non-positive position will send this code in to an endless recursion.一个非正的position会将此代码发送到无限递归中。

int digit(int number,int position){
        if(position==1) return number%10;
      return digit(number/10,--position);
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM