【发布时间】:2020-03-01 07:02:59
【问题描述】:
我正在尝试制作一个将二进制转换为十进制但需要显示转换过程的程序
输入一个二进制数:10110
1*(2^4) + 1*(2^2) + 1*(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;
}
【问题讨论】: