4.13 十进制/二进制转化器(C语言实现)

【题目描述】编写一个程序,将输入的十进制数转化为二进制表示。例如:输入十进制数64,输出二进制数1000000.

【代码实现】

c 复制代码
// 十进制/二进制转化器
# include <stdio.h>
int main()
{
    int num;
    printf("Please input a number:");
    scanf("%d", & num); // 输入十进制数 
    int a[50] = {0}, len = 0;
    if (num == 0) { // 十进制数0的二进制表示是0 
        ++len;
    }
    int tmp_num = num;
    while (tmp_num) { // 除2取余 
        a[len++] = tmp_num % 2;
        tmp_num /= 2;
    }
    printf("%d's binary representation:", num);
    for (int i = len - 1; i >= 0; --i) { // 逆序输出 
        printf("%d", a[i]);
    }
    return 0;
} 

【书上参考答案】

c 复制代码
# include "stdio.h"
# include <conio.h>
void deTobi(int a) // 将十进制数转化为二进制数,并打印在屏幕上 
{
    int i = 0, stack[10], r, s;
    do {
        r = a / 2; // 商
        s = a % 2; // 余数
        stack[i] = s;
        if (r != 0) {
            ++i;
            a = r; // 将a整除2的结果作为下一个整除2的对象 
        } 
    } while (r); // 循环直到商r为0为止
    for (; i >= 0; --i) {
        printf("%d", stack[i]);
    } 
    printf("\n");
}

int main()
{
    int a;
    printf("Please input a Decimal digit\n");
    scanf("%d", & a);
    deTobi(a);
    getche();
    return 0;
}
相关推荐
RuoZoe3 天前
重塑WPF辉煌?基于DirectX 12的现代.NET UI框架Jalium
c语言
祈安_6 天前
C语言内存函数
c语言·后端
norlan_jame8 天前
C-PHY与D-PHY差异
c语言·开发语言
czy87874758 天前
除了结构体之外,C语言中还有哪些其他方式可以模拟C++的面向对象编程特性
c语言
m0_531237178 天前
C语言-数组练习进阶
c语言·开发语言·算法
Z9fish8 天前
sse哈工大C语言编程练习23
c语言·数据结构·算法
代码无bug抓狂人8 天前
C语言之单词方阵——深搜(很好的深搜例题)
c语言·开发语言·算法·深度优先
CodeJourney_J8 天前
从“Hello World“ 开始 C++
c语言·c++·学习
枫叶丹48 天前
【Qt开发】Qt界面优化(七)-> Qt样式表(QSS) 样式属性
c语言·开发语言·c++·qt
with-the-flow8 天前
从数学底层的底层原理来讲 random 的函数是怎么实现的
c语言·python·算法