【发布时间】:2019-05-05 06:18:12
【问题描述】:
我正在使用 while 循环进行一些简单的十进制到二进制转换,我意识到我的循环输出需要反转,我这样做是通过创建一个字符串流然后将我生成的 int 移动到一个字符串流中然后将其转换为字符串,然后反转字符串的顺序以获得正确的二进制值...但是当我实际运行代码时,所有内容前面都有一个随机的 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
【问题讨论】: