【问题标题】:Binary number function二进制数功能
【发布时间】:2021-11-30 05:03:34
【问题描述】:
#include <iostream>
using namespace std;
void binary(unsigned  a) {
    int i;
    cout << "0" << endl;
    do {
        for (i = 1; i < a; i=i/2) {
            if ((a & i) != 0) {
                cout << "1" << endl;
            }
            else {
                cout << "0" << endl;
            
            }
    
        }
    }
    while (1 <= a && a <= 10);
}

int main(void) {
    binary(4);
    cout << endl;
}

我写了一个关于二进制数的代码。 İt 应该尊重输入数字,例如 for 4 (0100) 为 2 (10)。但是我的代码无穷无尽,你能解释一下吗?我在视觉上写 studio,我不能使用 因为在 Visual Studio 中没有这样的库

【问题讨论】:

  • 我在visual studio写的,不能使用因为visual studio中没有这样的库一件非常好的事情。永远不要使用这个标题。相关:https://stackoverflow.com/Questions/31816095/Why-Should-I-Not-Include-Bits-Stdc-H.
  • 问问自己:如果a4,那么while (1 &lt;= a &amp;&amp; a &lt;= 10) 什么时候结束?
  • @NathanOliver 它可以改变我刚刚写的。它应该起作用,我们的老师也可以给出另一个数字,但根据限制,它应该在 1 到 10 之间
  • 因为 Visual Studio 中没有这样的库 -- Visual Studio 万岁。 -- 还有我们的老师 -- 你的老师给你#include &lt;bits/stdc++.h&gt;?我希望不会。
  • 你应该在互联网上搜索“c++ binary number cout”或类似的东西。 StackOverflow 和互联网上都有很多类似的问题。

标签: c++ binary


【解决方案1】:

最初 i 为 1,但 i = i / 2i 设置为 0,并保持不变。因此,内部循环永远循环。

要以二进制形式输出unsigned 数字a,请使用

#include <bitset>
#include <climits>
std::cout << std::bitset<sizeof(a) * CHAR_BIT>(a) << '\n';

(在撰写本文时没有std::bin i/o 操纵器,参见std::hex。)

【讨论】:

  • sizeof(a) -- 你不需要乘以一个字节的位数吗?
  • @PaulMcKenzie:哎呀。
  • 非常感谢,但是老师说不能使用内置函数。
  • @SudeŞahin 但是我们的老师说你不能使用内置功能 -- 请提前发布你可以使用或不能使用的功能。否则你会有人浪费时间提出不被接受的合法答案(至少不会得到绿色的勾号)。
  • 确实,没有专业人士使用using namespace std;,因为它会导致命名空间污染。你显然还在使用std::cout
【解决方案2】:

不使用内置函数,您可以编写自己的函数并执行如下操作。

解决方案-1

#include <iostream>
void binary(unsigned int number)
{
    if (number / 2 != 0) {
        binary(number / 2);
    }
    std::cout << number % 2;
}

int main() {
    binary(10);
}

解决方案-2

#include <iostream>
#include<string>

void binary(unsigned int number)
{
    std::string str = "";
    while (number != 0) { 
        str = (number % 2 == 0 ? "0" : "1") + str;
        number /= 2; 
    }
    std::cout << str;
}
int main()
{
   binary(4);
}

注意:不要使用using namespace std;Why is "using namespace std;" considered bad practice?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-12
    • 2014-09-16
    • 2012-06-17
    • 2021-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多