
用C++编写用递归的方法把一个整数n转换成字符串。例如,输入483,应输出字符串“483”。
3个回答
展开全部
#include <iostream>
using namespace std;
//visualsan@yahoo.cn
void trans(char*buf,int pos,int n)
{
buf[ pos++ ] = n%10+'0';//保存个位数
if( n>= 10 )//如果有十位数,则进入递归
{
trans(buf,pos,n/10);
}else
{
buf[ pos ] = '\0';//字符串结束标志
//否则转换完成,但是此时的数组是反的,12345存为“54321”,
//因此需要头尾交换
int i=0;
while( i < pos/2 )
{
char tmp=buf[i];
buf[i] = buf[pos-i-1];
buf[pos-i-1]=tmp;
++i;
}
}
}
void main()
{
int pos=0;
char buf[100];
trans(buf,pos,123456789);
cout<<buf<<endl;
}
using namespace std;
//visualsan@yahoo.cn
void trans(char*buf,int pos,int n)
{
buf[ pos++ ] = n%10+'0';//保存个位数
if( n>= 10 )//如果有十位数,则进入递归
{
trans(buf,pos,n/10);
}else
{
buf[ pos ] = '\0';//字符串结束标志
//否则转换完成,但是此时的数组是反的,12345存为“54321”,
//因此需要头尾交换
int i=0;
while( i < pos/2 )
{
char tmp=buf[i];
buf[i] = buf[pos-i-1];
buf[pos-i-1]=tmp;
++i;
}
}
}
void main()
{
int pos=0;
char buf[100];
trans(buf,pos,123456789);
cout<<buf<<endl;
}
展开全部
#include <iostream>
using namespace std;
#define MAX 255
int pos = 0;
int exchange(int n, char *s)
{
int i = 0;
if(n != 0)
{
s[pos] = n % 10 + '0';
n /= 10;
exchange(n, s + 1); //递归调用
}
else if(n == 0) //转换完毕之后,字符串在倒叙一下
{
for(i = 0; i < pos; i++)
{
s[i] = s[i] + s[pos-1-i];
s[pos-1-i] = s[i] -s[pos-1-i];
s[i] = s[i] - s[pos-1-i];
}
return 0;
}
}
int main()
{
int m = 2356;
char cstr[MAX] = {0};
exchange(m, cstr);
cout << "cstr = "<<cstr << endl;
return 0;
}
using namespace std;
#define MAX 255
int pos = 0;
int exchange(int n, char *s)
{
int i = 0;
if(n != 0)
{
s[pos] = n % 10 + '0';
n /= 10;
exchange(n, s + 1); //递归调用
}
else if(n == 0) //转换完毕之后,字符串在倒叙一下
{
for(i = 0; i < pos; i++)
{
s[i] = s[i] + s[pos-1-i];
s[pos-1-i] = s[i] -s[pos-1-i];
s[i] = s[i] - s[pos-1-i];
}
return 0;
}
}
int main()
{
int m = 2356;
char cstr[MAX] = {0};
exchange(m, cstr);
cout << "cstr = "<<cstr << endl;
return 0;
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<time.h>
void out(int n,char s[])
{
if(n==0)return ;
out(n/10,s+1);
*s=n%10+'0';
}
int main(){
int n,i,j,tmp;
char s[100]={0};
puts("输入n");
scanf("%d",&n);
if(n==0)s[0]='0';
else out(n,s);
for(i=0,j=strlen(s)-1;i<=j;i++,j--)
{
tmp=s[i];
s[i]=s[j];
s[j]=tmp;
}
puts(s);
return 0;
}
#include<string.h>
#include<stdlib.h>
#include<time.h>
void out(int n,char s[])
{
if(n==0)return ;
out(n/10,s+1);
*s=n%10+'0';
}
int main(){
int n,i,j,tmp;
char s[100]={0};
puts("输入n");
scanf("%d",&n);
if(n==0)s[0]='0';
else out(n,s);
for(i=0,j=strlen(s)-1;i<=j;i++,j--)
{
tmp=s[i];
s[i]=s[j];
s[j]=tmp;
}
puts(s);
return 0;
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |