从 0 到 n 的二进制数,具有相同数量的字符/
Binary number from 0 to n having the same numbers of chars/
我想使proggram wchich将是二进制基数从o到n的通用数,我希望它们都具有相同数量的字符。 这就是代码:
#include <iostream>
#include <bitset>
#include <string>
#include <vector>
#include <cmath>
#include <stdio.h>
using namespace std;
vector<string> temp;
int BinaryNumbers(int number)
{
const int HowManyChars= ceil(log(number));
for(int i = 0; i<number; i++)
{
bitset<HowManyChars> binary(i);
temp.push_back(binary.to_string());
}
}
int main(){
BinaryNumbers(3);
for(int i=0; i<temp.size();i++)
{
cout<<temp[i]<<endl;
}
return 0;
}
我的问题是我无法设置位集<>数字(HowManyChars("[错误] 'HowManyChars' 无法出现在常量表达式中">
一种可能的解决方案是使用最大大小的bitset
来创建字符串。然后只返回字符串中的最后一个计数字符。
在 C++17 中有一个新功能to_chars
。 其中一个函数 (1( 采用最后一个参数的基础。
// use numeric_limits to find out the maximum number of digits a number can have
constexpr auto reserve_chars = std::numeric_limits< int >::digits10 + 1; // +1 for ' ' at end;
std::array< char, reserve_chars > buffer;
int required_size = 9; // this value is configurable
assert( required_size < reserve_chars ); // a check to verify the required size will fit in the buffer
// C++17 Structured bindings return value. convert value "42" to base 2.
auto [ ptr, err ] = std::to_chars( buffer.data(), buffer.data() + required_size, 42 , 2);
// check there is no error
if ( err == std::errc() )
{
*ptr = ' '; // add null character to end
std::ostringstream str; // use ostringstream to create a string pre-filled with "0".
str << std::setfill('0') << std::setw(required_size) << buffer.data();
std::cout << str.str() << 'n';
}
相关文章:
- visual在c++中将十进制数转换为二进制数
- 二进制数之和(使用C样式字符串)
- 如何循环访问 cpp 中的函数返回的字符指针数组
- 无法在声明时使用初始值设定项列表初始化常量字符*/字符串数组的向量
- 以 10 c++ 为基数显示 1024 位二进制数
- 根据字符获取数组的索引
- 二进制数和位标志'x'
- C++将常量字符* 指针数组传递给对象
- C++ 二进制数到整数值的数组
- 字符指针数组内存分配
- 二进制数组中最大连续 1 的起始和结束索引,以 C++ 为单位
- dev如何在C++中比较二进制数
- 递归回溯打印长度为N的二进制数的所有组合,而不使用循环
- 向后打印二进制数
- 如何为字符指针数组分配内存?
- 使用位黑客反转二进制数
- 添加两个二进制数(整数数组)
- 如何在字符指针数组中保留指向每个单词的指针?
- 从 0 到 n 的二进制数,具有相同数量的字符/
- 我通过迭代加法将二进制数转换为十进制并检查单个字符(请参阅代码)的方法有什么问题?