[英]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.