为什么在这个循环中十进制数没有变成二进制数?



为什么在这个计数器的值不断变化的循环中,十进制不转换为二进制,数字随机显示?

#include <iostream>
using namespace std;
int main()
{
int counter = 1, number, digit, result = 0;
cout << "DecimalttBinarytttOctaltHexadecimaln";
for (int i = 1; i <= 256; i++)
{
cout << dec << i << "t";
number = i;
do
{
digit = number % 2;
number /= 2;
result = result + counter * digit;
counter *= 10;
} while (number != 0);
cout << result << "t";
cout << oct << i << "t" << hex << i;
cout << endl;
}
return 0;
}

首先,resultint,因此这些值将像这样彼此递增,0 + 0 + 1 + 0 + 1,这将导致输出为2。这可以通过将结果设置为string类型来解决。

第二个问题是,您不需要每次都重置值。所以,随着时间的推移,这个值会继续增加,你需要重置循环中的值。

您可以使用以下方法方便地从decimal转换和打印您的数字到binary

#include <cmath>
#include <iostream>
int decimalToBinary(int N)
{
// To store the binary number
unsigned long long int binaryNumber = 0;
int counter = 0;
while (N != 0) {
int rem = N % 2;
unsigned long long int c = pow(10, counter);
binaryNumber += rem * c;
N /= 2;
// Count used to store exponent value
counter++;
}
return binaryNumber;
}
int main()
{
for (size_t i = 0; i < 256; i++)
{
std::cout << "Decimal=" << i << " " << "Binary=" << " " << decimalToBinary(i) << "n";
}
return 0;
}

在需要变量的最窄范围内声明变量,并在声明中初始化它们。

#include <iostream>
#include <iomanip>
int main()
{
std::cout << "DecimaltBinaryttOctaltHexadecimaln";
for (int i = 0; i < 256; i++)
{
int counter = 1;
int result = 0;

for (int number = i; number != 0; number /= 2)
{
int digit = number % 2;
result += (counter * digit);
counter *= 10;
}

std::cout << std::setfill('0') 
<< std::setw(3) << std::dec << i << "t" 
<< std::setw(8) << result << "t" 
<< std::setw(3) << std::oct << i << "t" 
<< std::setw(2) << std::hex << i << std::endl;
}
return 0;
}

然而,有一种更简单的方法来获得int二进制表示的字符串。

#include <bitset>
#include <iostream>
#include <iomanip>
int main()
{
std::cout << "DecimaltBinaryttOctaltHexadecimaln";
for (int i = 0; i < 256; i++)
{
std::cout << std::setfill('0') 
<< std::setw(3) << std::dec << i << "t" 
<< std::setw(8) << std::bitset<8>(i).to_string() << "t" 
<< std::setw(3) << std::oct << i << "t" 
<< std::setw(2) << std::hex << i << std::endl;
}
return 0;
}

首先,将整数转换为另一个整数,在打印成十进制后看起来像二进制数,这是一种疯狂的方法。

更合理的方法是创建一个函数,将整数转换为二进制数的文本表示形式。

std::string to_bin_string(int x) {
if (!x) return "0";
std::string s;
while (x) {
s += static_cast<char>(((x & 1) == 1) ? '1' : '0');
x >>= 1;
}
return { s.rbegin(), s.rend() };
}

https://godbolt.org/z/nv7zddnEc

有更好的方法,但这应该让你更清楚。