简体   繁体   English

在 C 中使用递归 function 反转数字

[英]Reversing digit using recursive function in C

I'm trying to create a recursive function to reverse digits of a number in C.我正在尝试创建一个递归 function 来反转 C 中数字的数字。 This is what I've written.这是我写的。 It works fine when used one time but when used multiple times it keeps piling the numbers together.一次使用时效果很好,但多次使用时它会不断地将数字堆积在一起。 I think the problem can be sorted if the sum is initialized to zero each time the function is called but I'm unable to do it.我认为如果每次调用 function 时总和都初始化为零,则问题可以解决,但我无法做到。 I've tried declaring sum=0 as a global variable but the result was the same.我尝试将 sum=0 声明为全局变量,但结果是一样的。 Input- 12 23 34 45 Output 21 2132 213243 21324354输入 - 12 23 34 45 Output 21 2132 213243 21324354

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int digit_reverse(int N)
{
int rem;
static int sum=0;
  if(N>0)
  {
      rem=N%10;
      sum=sum*10+rem;
      digit_reverse(N/10);
  }
  else
  return 0;
  return sum;
 }

 int main()
 {
 int a[25],i;

 for(i=0;i<4;i++)
 {
     scanf("%d", &a[i]);
 }
 printf("Output\n");
 for(i=0;i<4;i++)
 {
    printf("%d\n",digit_reverse(a[i]));
 }

 }

Maybe you can write your function without using static variables:也许您可以在不使用 static 变量的情况下编写 function :


void _digit_reverse(int N, int *sum)
{
    int rem;
    if (N > 0)
    {
        rem = N % 10;
        *sum = *sum * 10 + rem;
        _digit_reverse(N / 10, sum);
    }
}

int digit_reverse(int N)
{
    int sum = 0;
    _digit_reverse(N, &sum);
    return sum;
}

Or take the sum outside:或者在外面取总和:


int sum = 0;

int digit_reverse(int N)
{
    int rem;
    if (N > 0)
    {
        rem = N % 10;
        sum = sum * 10 + rem;
        digit_reverse(N / 10);
    }
    else
        return 0;
    return sum;
}

int main()
{
    int a[25], i;

    for (i = 0; i < 4; i++)
    {
        scanf("%d", &a[i]);
    }
    printf("Output\n");
    for (i = 0; i < 4; i++)
    {
        sum = 0;
        printf("%d\n", digit_reverse(a[i]));
    }
}

I believe that the static variable gets initialized only once.我相信 static 变量只被初始化一次。 This is the problem with your approach.这是您的方法的问题。

dude everything looks fine to me if the code do not needs to be reusable I can think of several solutions but keep in mind static and or global variables are not best practices unless necessarily required to.伙计,如果代码不需要可重用,我觉得一切都很好我可以想到几种解决方案,但请记住 static 和/或全局变量不是最佳实践,除非必须这样做。 secondly change your其次改变你的

// from static int sum = 0;
// to
static long sum = 0;
// or 
static long long sum = 0;

the reason for this error is value overflow an integer cannot have more than 4 bytes of data in this specific case you definitly needs more.此错误的原因是值溢出 integer 在这种特定情况下不能有超过 4 个字节的数据,您肯定需要更多。

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

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