#include<iostream> #include<cstring> using namespace std; int a[1000],b[1000]; string answer(int n){ int num=0,temp=0; while(n!=0){ a[num++]=n%2; n/=2; } for(int i=num-1;i>=0;i--){ if(a[i])b[++temp]=i; } string ans=""; for(int i=1;i<=temp;i++){ strcat(ans,strcat("2(",strcat(answer(b[i]),")+"))); } return substr(0,strlen(ans)-1); } int main(){ int n; cin>>n; cout<<answer(n); return 0; }
时间: 2023-12-05 13:06:46 浏览: 27
根据您提供的代码,出现错误的地方是在`return substr(0,strlen(ans)-1);`这一行。问题在于C++中没有名为`substr`的函数,您可能是想要使用`substr`函数来截取字符串的子串。此外,还需要包含`<string>`头文件。
请将`return substr(0,strlen(ans)-1);`修改为`return ans.substr(0,ans.length()-1);`,这样就可以正确地截取子串并返回了。
修改后的代码如下所示:
```cpp
#include<iostream>
#include<cstring>
using namespace std;
int a[1000],b[1000];
string answer(int n){
int num=0,temp=0;
while(n!=0){
a[num++]=n%2;
n/=2;
}
for(int i=num-1;i>=0;i--){
if(a[i])b[++temp]=i;
}
string ans="";
for(int i=1;i<=temp;i++){
ans += "2(" + answer(b[i]) + ")+";
}
return ans.substr(0,ans.length()-1);
}
int main(){
int n;
cin>>n;
cout<<answer(n);
return 0;
}
```
这样应该可以解决您遇到的问题。请注意,还要确保在使用字符串拼接时使用`+`操作符,而不是`strcat`函数。另外,建议在使用递归函数时先进行函数原型的声明,以避免出现其他问题。
相关推荐
![text/plain](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)