首页 > 解决方案 > 我如何编写一个使用递归将二进制字符串转换为十进制整数的程序来进行转换

问题描述

我似乎在我的程序中找不到任何错误。我对 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, 0) << endl;
    return 0;
}

它返回 14622728,提前感谢您提供的任何帮助 <3

标签: c++recursion

解决方案


#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, 0) << endl;
    return 0;
}

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


推荐阅读