二进制数函数


#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;
}

我写了一个关于二进制数的代码。伊特应该尊重比特输入数字,比如for4(0100)表示2(10)。然而,我的代码是无限的,你能解释一下吗。我写的是视觉studio和我不能使用<bits/stdc++.h>因为在视觉工作室中没有这样的库

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

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

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

(在写入时,没有std::bini/o操纵器。参见std::hex。)

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

解决方案-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;。为什么";使用命名空间std"被认为是不好的做法?