我用C语言编写了一个程序,将十进制数字转换为二进制,并将其存储在一个字符串中。问题不是反向打印的二进制文件,而是输出的显示方式
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int decimal;
// get the decimal from user
printf("Enter the decimal number: ");
scanf("%i", &decimal);
if(decimal == 1)
printf("The binary equivalent of %i is %i\n", decimal, decimal);
else
{
// considering binary is 64 bits in total
char bit[64];
int dividend, remainder, counter;
// we need decimal value intact so dividend copies it
dividend = decimal;
counter = 0;
do
{
remainder = dividend % 2;
if(remainder != 0)
bit[counter] = putchar('1');
else
bit[counter] = putchar('0');
// update the dividend and counter
dividend /= 2;
++counter;
// break if dividend has reached 1
if(dividend == 1)
break;
} while(dividend);
// print the final result
printf("The binary equivalent of %i is %s\n", decimal, bit);
}
return(0);
}
2的输出(反向应该是01 )提供了如下内容
$0二进制等价的2是0时间
小数点3
$1二进制等价物3是1倍
发布于 2017-06-02 13:23:46
你需要改变
if(dividend == 1)
至
if(dividend == 0)
也可以在循环之前使用memset
bit
到0,ie memset(bit,'\0',sizeof(bit));
。
https://stackoverflow.com/questions/44329851
复制相似问题