C++:二进制到十进制w/转换过程的外观

C++: Binary to Decimal w/ Appearance of the Conversion Process

本文关键字:转换 过程 外观 二进制 十进制 C++      更新时间:2023-10-16

我试图制作一个将二进制转换为十进制的程序,但需要显示转换的过程

输入二进制数字:10110

1*(2^4(+1*(2^2(+1*

10110的十进制等价物是:22

但相反,循环中间的计数器值没有降低,导致了这种

样本图像

这是我当前的代码

#include <iostream>
#include <math.h>
#include <string>
using namespace std;
int main()
{
int bin, dec = 0, remainder, num, base = 1,counter=0,counter2=0, constnum;
cout << "Enter the binary number: ";
cin >> num;
bin = num;
constnum = num;
while(bin > 0)
{
bin=bin/10;
counter2++;
}
while (num > 0)
{
if (num % 10 == 1) {
cout << " 1*(2^" << counter2 << ") +";
counter2--; 
}
else if(num % 10 == 0) {
counter2--;
}
remainder = num % 10; //get the last digit of the input
dec = dec + remainder * base;
base = base * 2;
num = num / 10;
}
cout << "nThe decimal equivalent of " << constnum << " : " << dec << endl;
return 0;
}

只需使用一个位集:

#include <bitset>
#include <iostream>
int main()
{
std::bitset<32> val;
std::cin >> val;
std::cout << val.to_ulong() << "n";
}

您应该按照升序而不是后代来编写过程,这是为了匹配您的算法,它是按照升序

所以,在你的最后一段时间,而不是这个:

if (num % 10 == 1) {
cout << " 1*(2^" << counter2 << ") +";
counter2--; 
}
else if(num % 10 == 0) {
counter2--;
}

你应该这样做:

if (num % 10 == 1) {
cout << " 1*(2^" << counter << ") +";
counter++;
}
else if(num % 10 == 0) {
counter++;
}

此外,如果你遵循我的建议,你可以删除你的第一个时间:

while(bin > 0)
{
bin=bin/10;
counter2++;
}

因为不再需要

如前所述,您正在以不同的顺序计算和显示结果。我建议您存储结果,稍后再显示。类似于:

#include <sstream>
....
int pos = 0;
string res;
while (num > 0) {
if (num % 10 == 1) {
stringstream out;
out << "1*(2^" << pos << ") + ";
res = out.str() + res;
}
remainder = num % 10; //get the last digit of the input
dec = dec + remainder * base;
base = base * 2;
num = num / 10;
pos++;
}
int len = res.length();
// to remove the last '+'
if (len >= 3) {
res = res.substr(0, len - 3);
}
cout << res;