[英]Decimal to Binary conversion using recursion with while loop
我的二进制转换在第二次再次出现后不起作用,它似乎仅在第一次使用时才起作用。 的目的是让用户输入一个数字,以将其从整数转换为十六进制,八进制和百分数,并继续询问和转换,直到用户输入0。请帮助!
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
long toBinary(int);
int main(void) {
int number = 0;
long bnum;
int zero = 0;
while(number != zero) {
puts("\nPlease enter a number you would like to convert to");
puts("\nHexadecimal, octal, and binary: ");
scanf("%d", &number);
if(number != zero) {
printf("\nThe Hexadecimal format is: %x", number);
printf("\nThe Octal format is: %o", number);
bnum = toBinary(number);
printf("\nThe binary format is: %ld\n", bnum);
}
else {
puts("\nI'm sorry you have to enter a number greater than 0.\n");
puts("\nOr have enter an invalid entry.");
}
}
return 0;
}
long toBinary(int number) {
static long bnum, remainder, factor = 1;
int long two = 2;
int ten = 10;
if(number != 0) {
remainder = number % two;
bnum = bnum + remainder * factor;
factor = factor * ten;
toBinary(number / 2);
}
return bnum;
}
您只需要一个函数即可将整数转换为其二进制表示形式。
假设int
是32位,那么这应该工作:
#include <stdio.h>
int main()
{
char str[33];
str[32] = 0;
int x = 13, loop;
for (loop = 31; loop >= 0; --loop) {
str[loop] = (x & 1) ? '1' : '0';
x = x >> 1;
}
printf("As %s\n", str);
return 0;
}
您可以将其变成函数,读取x等...
编辑
对于八进制/十六进制printf
将为您完成此操作
编辑
这里递归
#include <stdio.h>
void PrintBinary(int n, int x) {
if (n > 0) {
PrintBinary(n - 1, x >> 1);
}
printf("%c",(x & 1) ? '1' : '0');
}
int main()
{
PrintBinary(32,12);
return 0;
}
首先,我感到惊讶的是,它甚至一次可以工作。 首先,您的while条件是while号不等于零。 但是,立即开始,数字等于0,零等于0。因此,while应该永远不会运行。 如果要在主循环中保留此条件,请将其更改为do-while循环: do {// code} while(number!= 0); 。 这将至少运行一次代码,然后检查输入的数字是否不等于零。 那把我带到下一个问题。 您的scanf for number正在扫描一个double,并将其放置在常规整数存储位置中。 快速修复: scanf(“%i”,&number); 。 我也发现了一些称为puts的函数。我发现最好保留一个打印函数printf。 现在,我在您的toBinary函数中发现了一些错误,但是如果它能正常工作,我想它会起作用。 这些都是我能找到的错误,希望对您有所帮助。 但是,为了将来参考,在此级别无需声明像2或10这样的const数字的变量。
#include <stdint.h>
char* toBinary(int32_t number, int index){
static char bin[32+1] = {0}, *ret;
if(index == 32){
memset(bin, '0', 32);
return toBinary(number, 31);
} else if(number & (1<<index))
bin[31-index] = '1';
if(index)
(void)toBinary(number, index-1);
else
for(ret = bin; *ret == '0';++ret);
return ret;
}
...
int number = -1;
...
printf("\nThe binary format is: %s\n", toBinary(number, 32));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.