c++ - 我如何编写一个使用递归将二进制字符串转换为十进制整数的程序来进行转换
问题描述
我似乎在我的程序中找不到任何错误。我对 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
解决方案
#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;
}
我已经更正了您的代码并评论了修改。
推荐阅读
- node.js - 非优雅地终止 WebSocket 客户端连接
- asp.net - 如何配置子域名IIS
- python - Flask API 在导入套接字代码和 API 后给出 404
- database - 我在哪里可以找到 Oracle.DataAccess.dll?
- python - 在不同的python文件中使用变量
- javascript - Firebase:权限缺失或不足
- python - 数据中的重复模式
- html - 如何根据页面上其他位置的另一个元素的类来选择一个元素
- visual-c++ - C++ 如何打印 wstring?
- ajax - Spring Boot thymeleaf Ajax,响应有效,但不显示