我正在编写一个递归函数,它接受一个表示数字的 char 数组和一个指向该数组中数字的指针。该函数的要点是像++ 运算符一样递增数字。但是,当我尝试使用数字“819”时。它不会将其递增到“820”,而是将其更改为“810”(它递增最后一位数字但不执行我想要的递归)。有人可以帮我解决这个问题吗?谢谢。
#include <stdio.h>
char* inc(char *num, char* p)
{
if( *p>='0' && *p<='8' )
{
*p++;
}
else if ( *p=='9' )
{
*p = '0';
inc(num, --p);
}
return num;
}
main()
{
char x[] = "819";
printf("%s\n", inc(x, x+strlen(x)-1) ); //pass the number and a pointer to the last digit
}
最佳答案
将*p++改为(*p)++
;你想增加 p 中包含的数字。
char* inc(char *num, char* p)
{
if( *p>='0' && *p<='8' )
{
(*p)++; //==> change
}
else if ( *p=='9' )
{
*p = '0';
inc(num, --p);
}
return num;
}
编辑:
++
运算符的优先级高于 *
。因此,
*p++ ==> *p then p++; // p's value before the increment.
引用优先表here .
关于c - 递归增量器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/891715/