生成从1到n的二进制数的C程序 [英] c program to generate binary number starting from 1 till n

查看:40
本文介绍了生成从1到n的二进制数的C程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要这样的输出,如果数字是5,输出应该是从5到5的5个二进制数,但是从1开始已经给出了下面的例子。不使用数组即可完成此操作

输入:5 产量:1,10,11,100,101

但是我得到了 输出类似 这 输入=5 输出=1,11,11,111,111

此错误是因为指令错误吗 任何提示或解决方案

#include <stdio.h>
#include <math.h>
void binary_number(int n)
{

    int bin_n = 0;

    int i = 0;

    while (n > 0)
    {

        bin_n = n % 2;

        n = n / 2;

        i++;

    }
    for (int j = i - 1; j >= 0; j--)

        printf("%d", bin_n, j);

    printf("
");
}
void binary_number_generation(int n)
{
    for (int i = 0; i <= n; i++)

    {
        binary_number(i);
    }
}
int main()
{
    int n;

    printf("Enter the end value:");

    scanf("%d", &n);


    printf("
Binary Number from 1 to %d:", n);

    printf("
");

    binary_number_generation(n);

}

我在这里使用了一个新代码来标识我所做的事情,但它确实给出了结果

#include <stdio.h>
int main()
{
    int n,i=0,bin=0,plc,dig=0,j;
    printf("Enter the n value : ");
    scanf("%d",&n);
    printf("
Binary numbers from 1 to %d : ",n);
    for(i=0;i<=n;i++)
    {
        plc=0;bin=0;dig=0;
        for(plc=1,j=i;j>0;j=j/2)
        {
            dig=j%2;
            bin=bin+(dig*plc);
            plc=plc*10;
        }
        printf("%d
",bin);
    }
}

推荐答案

我们以6为例。

610=1*22+1*21+0*20=1102

通常,在构建二进制数时,您将使用数组。但是我们不能。但是如果我们能把110BASE 2(6)转换成数字110BASE 10(110)会怎么样。

11010=1*102+1*101+0*100

看起来可行!

6 base 10 = 1 * 2^2  + 1 * 2^1  + 0 * 2^0  = 110 base 2

            |          |          |
            v          v          v

            1 * 10^2 + 1 * 10^1 + 0 * 10^0 = 110 base 10

我们将此格式称为十进制编码的二进制(参考binary-coded decimal)。这将允许我们使用printf %d等打印数字。

解决方案如下。在继续阅读之前,您应该尝试自己实现它。


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

// Converts XYZ (base 2) to XYZ (base 10)
// 8 bit inputs require ceil(log2(11111111)) = 24 bit outputs.
// 16 bit inputs require ceil(log2(1111111111111111)) = 50 bit outputs.
uint64_t to_dcb(uint16_t n) {
   uint64_t dcb = 0
   uint64_t factor = 1;
   while (n > 0) {
      dcb += (n & 1) * factor;
      n >>= 1;
      factor *= 10;
   }

   return dcb;
}

int main(void) {
   printf("%" PRIu64 "
", to_dcb(6));
   return 0;
}

这篇关于生成从1到n的二进制数的C程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆