![](/img/trans.png)
[英]How can I cast an std::bitset<N> to an std::bitset<M>?
[英]C++ How can I assign an input value to a std::bitset argument?
我想制作一個簡單的程序,該程序將從輸入中獲取位數,並在輸出中顯示在給定位上寫入的二進制數(例如:我鍵入3:它顯示000、001、010、011、100、101、110 (111) 。 我遇到的唯一問題是在第二個for循環中,當我嘗試在bitset < bits >中分配變量時,它需要常數。 如果您能幫助我找到解決方案,我將非常感激。 這是代碼:
#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)。 您需要另一個將限制輸出的整數:
int x_temp = 10;
cin >> x_temp;
int const bits = 64;
...
這里64是您可以使用的某種最大值,因為bitset
的構造函數帶有unsigned long long
參數,該參數具有64位(至少;可能更多)。
但是,如果您將int
用於中間計算,則您的代碼可靠地最多支持14位(無溢出)。 如果要支持14位以上(例如64位),請使用更大的類型,例如uint32_t
或uint64_t
。
保留比所需更多的位的問題是將顯示其他位。 要刪除它們,請使用substr
:
cout << bitset<64>(...).to_string().substr(64 - x_temp);
在這里, to_string
將其轉換為64個字符的字符串,並且substr
剪切數字為x_temp
的最后一個字符。
您必須定義const int bits = 10; 作為全局常量:
#include <iostream>
#include <math.h>
#include <bitset>
using namespace std;
const unsigned bits=10;
int main() {
int maximum_value = 0,x_temp=10;
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.