如何编写使用递归将二进制字符串转换为十进制整数的程序

问题描述

我似乎无法在程序中找到任何错误。 我对C ++还是很陌生,无法理解我在网上找到的大多数示例。 这对我来说很有意义,但这也是我第一次尝试递归。 任何帮助将不胜感激。

#include "pch.h"
#include <iostream>
#include <cmath>
using namespace std;

int convert(string num,double dec_num,int i)
{
    if (i == num.length())
    {
        return dec_num;
    }
    else
    {
        dec_num += (pow(2,num.length()) * num[i]);
    }
    ++i;
    convert(num,dec_num,i);
}

int main()
{
    string binary = "101";
    cout << convert(binary,0) << endl;
    return 0;
}

它返回14622728,在此先感谢您提供的任何帮助

解决方法

#include "pch.h"
#include <iostream>
#include <cmath>
using namespace std;

int convert(string num,double dec_num,int i)
{
    if (i == num.length())
    {
        return dec_num;
    }
    else
    {
        dec_num += (pow(2,i) * (num[i]-'0')); //change here 
//        cout<<dec_num<<'\n';
    }
    ++i;
    return convert(num,dec_num,i); //change here 
}

int main()
{
    string binary = "101";
    cout << convert(binary,0) << endl;
    return 0;
}

我已更正您的代码并评论了修改。