鱼C论坛

 找回密码
 立即注册
查看: 989|回复: 2

[已解决]小甲鱼练习题-十进制转二进制(递归练习题)

[复制链接]
发表于 2020-2-18 21:25:44 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
#include <stdio.h>

int temp;
void transfer(unsigned long int);

int main()
{
        unsigned long num;
        printf("请输入一个正整数:");
        scanf("%lu",&num);
        transfer(num);
       
        return 0;
}

void transfer(unsigned int num)
{       
        temp=num%2;
        num=num/2;
        if(num!=0)
        {
                transfer(num);
                printf("%d",temp);
        }
        else
        {
                printf("%d",temp);
        }
}
呜呜呜,不知道为啥输出结果都是只有1
最佳答案
2020-2-18 21:57:58
每次调用transfer(),余数temp应该是独立的,不应该使用全局变量。修改如下:
  1. #include <stdio.h>
  2. void transfer(unsigned long);

  3. int main()
  4. {
  5.     unsigned long num;
  6.     printf("请输入一个正整数:");
  7.     scanf("%lu", &num);
  8.     transfer(num);

  9.     return 0;
  10. }

  11. void transfer(unsigned long num)
  12. {
  13.     int temp = num % 2;
  14.     num = num / 2;
  15.     if (num != 0)
  16.     {
  17.         transfer(num);
  18.         printf("%d", temp);
  19.     }
  20.     else
  21.     {
  22.         printf("%d", temp);
  23.     }
  24. }
复制代码


transfer()函数可以简化一下:
  1. void transfer(unsigned long num)
  2. {
  3.     int temp = num % 2;
  4.     num = num / 2;
  5.     if (num != 0)
  6.         transfer(num);
  7.     printf("%d", temp);
  8. }
复制代码

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2020-2-18 21:57:58 | 显示全部楼层    本楼为最佳答案   
每次调用transfer(),余数temp应该是独立的,不应该使用全局变量。修改如下:
  1. #include <stdio.h>
  2. void transfer(unsigned long);

  3. int main()
  4. {
  5.     unsigned long num;
  6.     printf("请输入一个正整数:");
  7.     scanf("%lu", &num);
  8.     transfer(num);

  9.     return 0;
  10. }

  11. void transfer(unsigned long num)
  12. {
  13.     int temp = num % 2;
  14.     num = num / 2;
  15.     if (num != 0)
  16.     {
  17.         transfer(num);
  18.         printf("%d", temp);
  19.     }
  20.     else
  21.     {
  22.         printf("%d", temp);
  23.     }
  24. }
复制代码


transfer()函数可以简化一下:
  1. void transfer(unsigned long num)
  2. {
  3.     int temp = num % 2;
  4.     num = num / 2;
  5.     if (num != 0)
  6.         transfer(num);
  7.     printf("%d", temp);
  8. }
复制代码

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

 楼主| 发表于 2020-2-18 22:02:01 | 显示全部楼层
superbe 发表于 2020-2-18 21:57
每次调用transfer(),余数temp应该是独立的,不应该使用全局变量。修改如下:

感谢感谢,原来是这个
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-13 18:58

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表