我有这个代码将十进制数转换为二进制数:
#include <iostream>
#include <windows.h>
#include <vector>
#include <algorithm>
using namespace std;
void space(){ cout << endl << endl << endl; }
int main(int argc, char const *argv[]){
system("color 1F");
unsigned long int n, copy_n;
vector<int> v;
cout << "# Decimal: "; cin >> n; cout << endl; copy_n = n;
while (n != 0){
if (n % 2 == 0){ v.push_back(0); }else{ v.push_back(1); }
n = int(n / 2);}
cout << endl << "# Binary: ";
reverse(v.begin(), v.end());
for (size_t i = 0; i < v.size(); i++){cout << v.at(i);}
space(); system("Pause"); return 0;
}
......而这......
#include <iostream>
#include <windows.h>
using namespace std;
void space(){ cout << endl << endl << endl; }
int main(int argc, char const *argv[]){
system("color 1F");
unsigned long int n, copy_n, nr = 0 ;
cout << "# Decimal: "; cin >> n; copy_n = n; cout << endl;
while (copy_n != 0){ nr++; copy_n = int(copy_n / 2); }
int* v = new int[nr];
for (int i = 0; i < nr; i++){if (n % 2 == 0){ v[i] = 0; }else{ v[i] = 1; }n = int(n / 2);}
cout << endl << "# Binary: ";
for (int i = nr-1; i >= 0;i--){cout << v[i] << "";}
space(); system("Pause"); return 0;}
......而这......
#include <iostream>
#include <windows.h>
#include <bitset>
using namespace std;
void space(){ cout << endl << endl << endl; }
int main(int argc, char const *argv[]){
system("color 1F");
unsigned int n;
cout << "# Decimal: "; cin >> n; cout << endl;
bitset<16>binary(n);
cout << endl << "# Binary: " << binary << endl;
space(); system("Pause"); return 0;
}
但我的问题是:
如何使用算法中的reverse()函数并使用基于范围的for循环
打印矢量例如:十进制= 2
带
reverse(v.begin(), v.end());
for (size_t i = 0; i < v.size(); i++){cout << v.at(i);}
程序打印10
带
reverse(v.begin(), v.end());
for(auto i : v){cout<<v.at(i);}
程序pritns 01
为什么呢?我该如何解决这个问题?
答案 0 :(得分:2)
这句话
reverse(v.begin(), v.end());
for(auto i : v){cout<<v.at(i);}
完全错了。
有效代码看起来像
reverse(v.begin(), v.end());
for(auto i : v){ cout << i;}
此外,如果您为源代码中输入的符号数付款,则此声明
if (n % 2 == 0){ v.push_back(0); }else{ v.push_back(1); }
看起来非常好,因为它包含许多符号。否则最好写
v.push_back( n % 2 );
同样在你的一个程序中,你动态分配一个数组
int* v = new int[nr];
但不是免费的。在这种情况下,最好使用智能指针std::unique_ptr
。
您也可以尝试编写递归函数。例如
#include <iostream>
#include <vector>
std::vector<unsigned int> & dec_to_bin( std::vector<unsigned int> &v,
unsigned int x )
{
const unsigned int Base = 2;
static size_t n;
unsigned int digit = x % Base;
++n;
if ( x /= Base )
{
dec_to_bin( v, x );
}
else
{
v.reserve( n );
n = 0;
}
v.push_back( digit );
return v;
}
int main()
{
while ( true )
{
std::cout << "Enter a non-negative number (0-exit): ";
unsigned int x = 0;
std::cin >> x;
if ( !x ) break;
std::vector<unsigned int> v;
dec_to_bin( v, x );
for ( auto digit : v ) std::cout << digit;
std::cout << std::endl;
}
return 0;
}
如果要按顺序输入
15
7
3
1
0
然后程序输出
Enter a non-negative number (0-exit): 15
1111
Enter a non-negative number (0-exit): 7
111
Enter a non-negative number (0-exit): 3
11
Enter a non-negative number (0-exit): 1
1
Enter a non-negative number (0-exit): 0