我正在使用while循环进行一些简单的十进制到二进制的转换,我意识到循环的输出需要反转,这是通过创建一个stringstream然后将生成的int移到stringstream中来实现的。将其转换为字符串,然后颠倒字符串的顺序以获取正确的二进制值...但是当我实际运行代码时,在所有内容前面都有一个随机的1或0 ...
#include <iostream>
#include <sstream>
#include <algorithm>
int main() {
std::stringstream ss;
int decimal;
int binary;
std::cout<< "\n Please enter decimal value: ";
std::cin >> decimal;
std::cout << "\n The binary equivalent of " << decimal << " is ";
while(decimal > 0 ) {
binary = decimal % 2;
decimal/= 2;
std::cout << binary;
}
ss << binary;
std::string binary_string = ss.str();
std::reverse(binary_string.begin(), binary_string.end());
std::cout << binary_string;
}
例如,如果我输入11,我会得到:
Please enter decimal value: 11
The binary equivalent of 11 is 11011
对于12:
Please enter decimal value: 12
The binary equivalent of 12 is 00111
答案 0 :(得分:0)
有两个问题。
ss << binary
行应放在循环内
您应该从循环中删除cout << binary
看起来像这样
int decimal;
int binary;
cout<< "\n Please enter decimal value: ";
cin >> decimal;
cout << "\n The binary equivalent of " << decimal << " is ";
while(decimal > 0 ) {
binary = decimal % 2;
decimal/= 2;
ss << binary;
}
string binary_string = ss.str();
reverse(binary_string.begin(), binary_string.end());
cout << binary_string;
}
答案 1 :(得分:0)
多余的钱来自
ss << binary;
string binary_string = ss.str();
reverse(binary_string.begin(), binary_string.end());
cout << binary_string;
在循环之后。 binary
将包含一个1
或一个0
,然后将其转换为字符串并将其反转将为您提供相同的功能。您需要将ss << binary;
移入循环,以便它包含您生成的所有二进制数字。