问题描述
我想编写一个简单的程序,该程序将从输入中获取位数,并在输出中显示在给定位数上写入的二进制数(示例:我键入3:它显示000、001、010、011 ,100、101、110、111).我遇到的唯一问题是在第二个 for 循环中,当我尝试在 bitset< bits > 中分配变量时,它想要常量数字.如果您能帮助我找到解决方案,我将非常感激.这是代码:
I want to make a simple program that will take number of bits from the input and as an output show binary numbers, written on given bits (example: I type 3: it shows 000, 001, 010, 011, 100, 101, 110, 111).The only problem I get is in the second for-loop, when I try to assign variable in bitset<bits>, but it wants constant number.If you could help me find the solution I would be really greatful.Here's the code:
#include <iostream>
#include <bitset>
#include <cmath>
using namespace std;
int main() {
int maximum_value = 0,x_temp=10;
//cin >> x_temp;
int const bits = x_temp;
for (int i = 1; i <= bits; i++) {
maximum_value += pow(2, bits - i);
}
for (int i = maximum_value; i >= 0; i--)
cout << bitset<bits>(maximum_value - i) << endl;
return 0;
}
推荐答案
数字(非类型",如C ++所称)模板参数必须为编译时常量,因此您不能使用用户提供的数字.请改用较大的常数(例如64).您需要另一个将限制输出的整数:
A numeric ("non-type", as C++ calls it) template parameter must be a compile-time constant, so you cannot use a user-supplied number. Use a large constant number (e.g. 64) instead. You need another integer that will limit your output:
int x_temp = 10;
cin >> x_temp;
int const bits = 64;
...
这里64是您可以使用的某种最大值,因为bitset
具有一个带有unsigned long long
参数的构造函数,该参数具有64位(至少;可能更多).
Here 64 is some sort of a maximal value you can use, because bitset
has a constructor with an unsigned long long
argument, which has 64 bits (at least; may be more).
但是,如果在中间计算中使用int
,则您的代码最多可靠地支持14位(无溢出).如果要支持14位以上的字符(例如64位),请使用更大的类型,例如uint32_t
或uint64_t
.
However, if you use int
for your intermediate calculations, your code supports a maximum of 14 bits reliably (without overflow). If you want to support more than 14 bits (e.g. 64), use a larger type, like uint32_t
or uint64_t
.
保留比所需的位数更多的一个问题是将显示其他位数.要删除它们,请使用substr
:
A problem with holding more bits than needed is that the additional bits will be displayed. To cut them out, use substr
:
cout << bitset<64>(...).to_string().substr(64 - x_temp);
此处to_string
将其转换为具有64个字符的字符串,并且substr
剪切最后一个字符,其编号为x_temp
.
Here to_string
converts it to string with 64 characters, and substr
cuts the last characters, whose number is x_temp
.
这篇关于C ++如何为std :: bitset参数分配输入值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!