2009-05-21 75 views
2

我正在写一个递归函数,它需要一个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 
} 

回答

11

变化*p++ to (*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

+0

我以为* p ++会在p实际增加之前返回* p的值? – 2009-05-21 07:39:10

+0

您的编辑错误。我的意思是你的优先权声明是正确的,但你没有考虑到后增加延迟到声明结束。 – paxdiablo 2009-05-21 07:41:47

4

这是因为*p++检索字符,然后增加指针。你想(*p)++这在指针递增字符:

#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; 
} 

你应该对上面9XXX串运行此非常小心,因为你必须确保你离开房间的一位数上(预如有必要,填写0)。如预期

820 
9000 
0000 
aaa73 
aaa280 
aaa0000 

:在

#include <stdio.h> 

char *inc (char *num, char* p) { 
    if (p < num) 
     return num; 
    if ((*p < '0') || (*p > '9')) 
     return num; 
    if (*p < '9') { 
     (*p)++; 
     return num; 
    } 
    *p = '0'; 
    return inc(num, --p); 
} 

int main (int argc, char *argv[]) { 
    char x[] = "819"; 
    char y[] = "8999"; 
    char z[] = "9999"; 
    char a[] = "aaa72"; 
    char b[] = "aaa279"; 
    char c[] = "aaa9999"; 
    printf("%s\n", inc(x, x+strlen(x)-1)); 
    printf("%s\n", inc(y, y+strlen(y)-1)); 
    printf("%s\n", inc(z, z+strlen(z)-1)); 
    printf("%s\n", inc(a, a+strlen(a)-1)); 
    printf("%s\n", inc(b, b+strlen(b)-1)); 
    printf("%s\n", inc(c, c+strlen(c)-1)); 
    return 0; 
} 

这段代码的结果:否则加保护,如下面的换行功能。

1

我公司始终遵循的一些准则,在C++编码时帮助达到正确性:

  • 不要修改并获得相同的指令 任何东西的价值。inc(num, --p);被禁止 因为inc的第二个参数是 而不是const。
  • 千万不要取消引用 指针,并在 中使用同一行。即所有形式的 (*p)++;被禁止。
  • 总是保证函数参数的const-correctness。
  • 命令/查询分隔函数通常应该是const或void。
  • 不要使用 递归如果你可以避免它,即总是先查找一个非递归的选择。 (这个问题是一个你可以避免的例子)。
  • 按合同设计。将前提条件添加到 开头,并将后续条件添加到 函数末尾。

将它们应用到你的函数可能有助于消除它中的错误。

0

的原始节目的副作用的例子作为GCC编译,(此副作用不会发生在@Pax程序)

int 
main() 
{ 
char x[] = "9"; 
char z[] = {57,57,57,57}; 

int t=0; 
for(t=0;t<4;++t) 
    printf("z == %d\n",z[t]); 

inc(x, x+strlen(x)-1); 

for(t=0;t<4;++t) 
    printf("z == %d\n",z[t]); 

}

输出: ž == 57 ž== 57 ž== 57 ž== 57 ž== 48 ž== 48 ž== 48 ž== 48