【问题标题】:Decimal to Binary Conversion十进制到二进制转换
【发布时间】:2023-04-11 04:13:02
【问题描述】:

我正在编写一个用于在十进制和二进制基数系统之间进行转换的函数,这是我的原始代码:

void binary(int number)
{
    vector<int> binary;

    while (number == true)
    {
        binary.insert(binary.begin(), (number % 2) ? 1 : 0);
        number /= 2;
    }

    for (int access = 0; access < binary.size(); access++)
        cout << binary[access];
}

在我这样做之前它没有工作:

while(number)

怎么了

while(number == true)

这两种形式有什么区别? 提前致谢。

【问题讨论】:

    标签: c++ while-loop evaluation conditional-statements boolean-expression


    【解决方案1】:

    当你说while (number)number,这是一个int,被转换为类型bool。如果为零,则变为false,如果为非零,则变为true

    当你说while (number == true) 时,true 被转换为int(变成1),就像你说while (number == 1) 一样。

    【讨论】:

    • 感谢您的澄清,我还在学习中,有时类型提升会逃避我。
    【解决方案2】:

    这是我的代码....

        #include<stdio.h>
    #include<string.h>
    #include<stdlib.h>
    #include<math.h>
    #include<unistd.h>
    #include<assert.h>
    #include<stdbool.h>
    #define max 10000
    #define RLC(num,pos) ((num << pos)|(num >> (32 - pos)))
    #define RRC(num,pos) ((num >> pos)|(num << (32 - pos)))
    
    void tobinstr(int value, int bitsCount, char* output)
    {
        int i;
        output[bitsCount] = '\0';
        for (i = bitsCount - 1; i >= 0; --i, value >>= 1)
          {
                 output[i] = (value & 1) + '0';
          }
    }
    
    
      int main()
       {
        char s[50];
        tobinstr(65536,32, s);
        printf("%s\n", s);
        return 0;
       }
    

    【讨论】:

      猜你喜欢
      • 2016-02-09
      • 2016-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-27
      相关资源
      最近更新 更多