【发布时间】:2020-06-03 17:29:34
【问题描述】:
对于这个程序,我将输入一个二进制数,它将转换为十进制数。最后,我想返回我输入的二进制数中的位数。例如,1001 - 4 二进制数。二进制数的位数输出始终为 0。我应该使用 size_type 吗?
#include<iostream>
#include<string>
#include<bitset>
#include<limits>
#include<algorithm>
using namespace std;
int multiply(int x);
int multiply(int x)
{
if (x == 0)
{
return 1;
}
if (x == 1)
{
return 2;
}
else
{
return 2 * multiply(x - 1);
}
}
int count_set_bit(int n)
{
int count = 0;
while (n != 0)
{
if (n & 1 == 1)
{
count++;
}
n = n >> 1;
}
return count;
}
int main()
{
string binary;
cout << "\n\tDualzahlen : ";
cin >> binary;
reverse(binary.begin(), binary.end());
int sum = 0;
int size = binary.size();
for (int x = 0; x < size; x++)
{
if (binary[x] == '1')
{
sum = sum + multiply(x);
}
}
cout << "\tDezimal : " << sum << endl;
int n{};
cout << "\tAnzahl der Stelle : " << count_set_bit(n) << endl;
}
【问题讨论】:
-
二进制数的大小为
binary.size()。不确定你想用int n{}; cout << "\tAnzahl der Stelle : " << count_set_bit(n) << endl;做什么,因为n是零,你总是会得到零 -
仔细查看参数
n:int n{};->count_set_bit(n)->while (n != 0)。此时n将具有什么价值?n应该是什么? -
您的
count_set_bits函数以二进制形式计算1的位数(因此对于 1001,结果为 2),而不是总位数。
标签: c++