小甲鱼练习题-十进制转二进制(递归练习题)
#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 每次调用transfer(),余数temp应该是独立的,不应该使用全局变量。修改如下:
#include <stdio.h>
void transfer(unsigned long);
int main()
{
unsigned long num;
printf("请输入一个正整数:");
scanf("%lu", &num);
transfer(num);
return 0;
}
void transfer(unsigned long num)
{
int temp = num % 2;
num = num / 2;
if (num != 0)
{
transfer(num);
printf("%d", temp);
}
else
{
printf("%d", temp);
}
}
transfer()函数可以简化一下:
void transfer(unsigned long num)
{
int temp = num % 2;
num = num / 2;
if (num != 0)
transfer(num);
printf("%d", temp);
}
superbe 发表于 2020-2-18 21:57
每次调用transfer(),余数temp应该是独立的,不应该使用全局变量。修改如下:
感谢感谢,原来是这个{:5_108:}
页:
[1]