用递归法将一个整数n转换成字符串。例如,输入123,应输出字符串“321”。整数n的位数不确定,可以是任意的整数。
#include<stdio.h>
void convert(int n) {
int i;
putchar(n % 10 + '0');
if ((i = n / 10) != 0)
convert(i);
}
int main() {
int num;
scanf("%d", &num);
if (num < 0) {
printf("-");
num = -num;
}
convert(num);
printf("\n");
return 0;
}
递归法:
void trans(int n, char *s)
{
*s++ = '0'+ n%10;
if (n!=0)
trans(n/10, s);
else
*--s='\0';
}
int main ()
{
int n;
char str[10]; //整型最多9位数
scanf("%d",&n);
trans(n, str);
printf("%s", str);
return 0;
}
普通法:
#include <stdio.h>
void trans(int n, char *s)
{
while (n){
*s++ = '0'+ n%10;
n /= 10;
}
*s='\0';
}
int main ()
{
int n;
char str[10]; //整型最多9位数
scanf("%d",&n);
trans(n, str);
printf("%s", str);
return 0;
}
没考虑负数,要的话修改下
整数转换成字符串s,并输出字符串s
你题目的解答代码如下:
#include <stdio.h>
void reversed(int n, char s[], int i)
{
s[i] = n % 10 + '0';
if (n / 10 == 0)
s[i + 1] = '\0';
else
reversed(n/10, s, i+1);
}
int main()
{
long long int n;
char s[100];
scanf("%lld", &n);
reversed(n, s, 0);
printf("%s\n", s);
return 0;
}
如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!
#include<stdio.h>
#include<stdlib.h>
int main(){
char ans[1000];
long long a,cnt=-1;
scanf("%lld",&a);
while(a){
ans[++cnt]=a%10+'0';
a/=10;
}
printf("%s",ans);
return 0;
}
数字+'0'就变成了字符串