gpt4 book ai didi

不使用数组将十进制转换为二进制

转载 作者:行者123 更新时间:2023-11-30 20:16:52 24 4
gpt4 key购买 nike

问题:编写一个不使用数组将十进制数转换为二进制数的程序

我所做的是:

#include<stdio.h>
#include<stdlib.h>

int main() {
int rem,n,rev=0;
scanf("%d",&n);
while(n>0) {
rem=n%2;
n=n/2;
printf("%d",rem);
}
}

在 while 循环中,当 n>0 时,我已将余数存储在 rem 变量和 n/=2 中> 和 printf rem

现在我想反转rem,所以我使用正常方法反转数字,但零没有出现,该怎么办?

喜欢输入:4输出应该是:0010输出即将到来:1输入:8输出应该是:1000输出为1像这样

最佳答案

下面说明了两种方法:迭代和递归:

#include <stdint.h>
#include <stdio.h>

void printBinaryIterative(uint32_t num)
{
uint32_t bit = 0x80000000;

while(bit)
{
if(bit & num)
printf("1");
else
printf("0");

bit >>= 1;
}
}

void printBinaryRecursive(uint32_t num)
{
if(num / 2)
printBinaryRecursive(num / 2);

printf("%u", num % 2);
}

int main(void)
{
uint32_t num;

printf("Iterative\n");
num = 0x00000001;
printf("0x%08X = ", num);
printBinaryIterative(num);
printf("\n");

num = 0x80000000;
printf("0x%08X = ", num);
printBinaryIterative(num);
printf("\n");

num = 0x5CA1AB1E;
printf("0x%08X = ", num);
printBinaryIterative(num);
printf("\n");

printf("Recursive\n");
num = 0x00000001;
printf("0x%08X = ", num);
printBinaryRecursive(num);
printf("\n");

num = 0x80000000;
printf("0x%08X = ", num);
printBinaryRecursive(num);
printf("\n");

num = 0x5CA1AB1E;
printf("0x%08X = ", num);
printBinaryRecursive(num);
printf("\n");

return 0;
}

产生以下输出:

$ gcc main.c -o main.exe; ./main.exe;Iterative0x00000001 = 000000000000000000000000000000010x80000000 = 100000000000000000000000000000000x5CA1AB1E = 01011100101000011010101100011110Recursive0x00000001 = 10x80000000 = 100000000000000000000000000000000x5CA1AB1E = 1011100101000011010101100011110

关于不使用数组将十进制转换为二进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59652383/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com