繁体   English   中英

使用递归获取数字中的数字位置

[英]Getting the position of a digit in a number using recursion

我目前正在编写一个代码,它返回用户输入的某个数字的位置。 我目前正面临一个问题,我的指针不起作用,我认为这是由于递归函数。 任何意见,将不胜感激!

#include <stdio.h>

void rDigitPos2(int num, int digit, int *pos);

int main()
{
    int number;
    int digit, result = 0;
    printf("Enter a number: ");
    scanf("%d", &number);
    printf("Enter the digit: ");
    scanf("%d", &digit);
    rDigitPos2(number, digit, &result);
    printf("rDigitPos2(): %d", result);
    return 0;
}

void rDigitPos2(int num, int digit, int *pos) {
    static int count = 0;
    if (num % 10 != digit) { 
    count++; //increment of position
    rDigitPos2(num/10, digit, &pos);

    *pos = count;//returns the position of the digit
}
rDigitPos2(num/10, digit, &pos);

rDigitPos2(num/10, digit, pos);

由于参数(pos)已经在第一次调用中传递给函数,因此在递归调用中传递(&pos)将导致传递(pos)的地址

一些改进

  • 输入数字没有出现在数字中时,您还需要正确处理案例
  • 您从最后一位开始提供头寸,而不是从头开始。 (你的计数也从0开始,而不是1
  • 在函数调用中包含(digit)参数多余的 ,因为它是常量。

- 快乐编码:)

更改

rDigitPos2(num/10, digit, &pos);

rDigitPos2(num/10, digit, pos);

以及细节

GCC编译器发出重要警告,用&pos替换&pos pos

ss.c:20:31: warning: incompatible pointer types passing 'int **' to parameter of type 'int *'; remove & [-Wincompatible-pointer-types]
    rDigitPos2(num/10, digit, &pos);
                              ^~~~

谦虚的要求,请不要忽视警告:)

有效地返回rDigitPos2的1个基本位置

void rDigitPos2(int num, int digit, int *pos)
{
    static int count = 0;
    if (num % 10 != digit)
    {
        count++; //increment of position
        rDigitPos2(num/10, digit, pos);   //Not &pos

    }
    else
    {
        *pos = count;     //Current position from the last
        while(num!=0)
        {
            num = num/10;
            count++;
        }
        *pos = count-*pos;  //Original position form beginning
    }
}

当你的递归的第一部分从最后一个找到位置时,需要找到数字的长度,然后length-position from last将是你的答案。

暂无
暂无

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

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