用C++编写一个递归函数将一个整数n转换成相应的字符串

#include<iostream>
using namespace std;
int main()
{int a;
cin>>a;
int zhishu(int);
char f(int);
f(a);
cout<<'\n';
return 0;
}
int zhishu(int n)
{if(n)
{n-=1;
return 10*zhishu(n);}
if(n==0)
return 1;
}
char f(int n)
{int p=0;
while(n)
{n=n/10;
p++;}
cout<<char(n/zhishu(p-1)+48);
n=n-(n/zhishu(p-1))*zhishu(p-1);
if(n)
return f(n);

我输出的是0,为什么,哪里错了,怎么改啊

zhishu这个函数没什么意义啊

char f(int n )
{
    int m=n/10;
    char c= n%10 + '0';

    if(m)
     cout<<f(n/10)<<c;
    else
       return(c);
         
     
         
  }

追问

其实zhishu的意思是10的多少次方,我的意思是比如345就%10的平方,就是zhishu(2),
不对啊,我输入345,
输出的是34p5,你可以运行试一下

追答

给你个完整的程序:

#include <iostream>
using namespace std;
void f(int n );

int main() {
int n;
   cin>>n;
   f(n);
return 0;
}

void f(int n)
{
    int m=n/10;
    char c= n%10 + '0';
    if(m)
{  f(m); cout<<c;}
    else
     cout<<(c);
  }

追问

你原来那个看起来也对,但为什么会输出不对?
还有这种方法好巧妙,你怎么想到的?

温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-12-28
将一个整数n转换成相应的字符串
题目是什么意思?
举个例子,方便检查程序追问

就是比如一个int a=345;
变成char a="345";

追答

#include
#include
using namespace std;
int main()
{
int a;
cin>>a;
char s[20];
sprintf(s, "%d", a );
cout << s <<endl ;
return 0;
}

追问

sprintf(s, "%d", a );

这句看不懂啊,没学过C,只学了C++

追答

编程无定式,多学多研究
sprintf()是C语言中的一个格式化转换数据的函数,方便将任意数据转换成字符串,或称之为以字符形式存储到字符串中。详情可查阅相关资料。

相似回答