将十进制转换为二进制的C程序

时间:2017-06-02 13:12:00

标签: c string algorithm gcc integer

我在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次

2 个答案:

答案 0 :(得分:1)

我们初学者应该互相帮助。:)

你在这里。

#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>是多余的,可能会被删除。

答案 1 :(得分:0)

您需要更改

  if(dividend == 1)

  if(dividend == 0)

在使用之前memset bit也为0,即在循环之前memset(bit,'\0',sizeof(bit));