我用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:36:59
我们初学者应该互相帮助。
给你。
#include <stdio.h>
int main(void)
{
unsigned int decimal;
// get the decimal from user
printf("Enter the decimal number: ");
scanf("%u", &decimal);
// considering binary is 64 bits in total
char bit[64];
unsigned int dividend, remainder, counter;
// we need decimal value intact so dividend copies it
dividend = decimal;
counter = 0;
do
{
remainder = dividend % 2;
bit[counter++] = remainder + '0';
} while( dividend /= 2 );
bit[counter] = '\0';
// print the final result
printf("The binary equivalent of %u is %s\n", decimal, bit);
return 0;
}
程序输出可能类似于
Enter the decimal number: 2
The binary equivalent of 2 is 01
至于您的代码,那么这个代码片段
if(decimal == 1)
printf("The binary equivalent of %i is %i\n", decimal, decimal);
else
是多余的。
这个代码片段
if(remainder != 0)
bit[counter] = putchar('1');
else
bit[counter] = putchar('0');
没有任何意义。如上面的演示程序所示,您需要编写
bit[counter++] = remainder + '0';
从循环中退出
if(dividend == 1)
break;
是错的。
还需要将结果字符串附加到终止为零的字符串中。
另外,由于您没有考虑输入数字的符号,所以最好将其声明为具有unsigned int
类型。
考虑到头、<string.h>
和<stdlib.h>
是多余的,并且可能被删除。
发布于 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
复制相似问题