本文目錄一覽:
- 1、C語言題目:使用遞歸法將整數轉換成字元串。
- 2、C語言編程:用遞歸法將一個整數n轉換成字元串。
- 3、數字轉字元串C語言(必須用遞歸演算法)
- 4、C語言用遞歸法將一個整數n轉換成字元串的程序中 putchar(n%10+’0′);有什麼作用?
- 5、C語言,請問:遞歸函數把整數轉換成字元串:如123,字元串「123」怎麼做?非常急
- 6、用遞歸將一個整數n轉換成一個字元串。如將1234轉換為”1234″。
C語言題目:使用遞歸法將整數轉換成字元串。
可以這樣用ascii碼來轉換
ascii碼從48~58分別是0,1,2…9
int a=3;
char b;
b=char(a+48);
然後b就是字元’3’了
#includestdio.h
char mychar[100];//定義一個無限大的字元數組來存放所生成的字元 不過最好使用c的動態內存分配
int i=0;
char* function(int a)
{
if (a10) {
mychar[i++]=char(48+a);
return mychar;
}
function(a/10);
mychar[i++]=char(48+a%10);//轉化為字元串使用ascii碼來轉換
return mychar;
}
void main()
{
char*a;
int num=0;
scanf(“%d”,num);
a=function(num);
printf(“轉化為字元串後:%s”,a);
}
C語言編程:用遞歸法將一個整數n轉換成字元串。
你好!
你不是用遞歸做的,如果只是簡單的輸出,可以這樣做:
void
tran(int
a)
{
if(a=10)
tran(a/10);
printf(“%d”,a%10);
}
void
main()
{
tran(12345);
}
希望對你有所幫助,望採納。
數字轉字元串C語言(必須用遞歸演算法)
#include stdio.h
#include math.h
int Digit(int n)
{
int d = 0;
do{
++d;
n /= 10;
}while(n 0 || n 0);
return d;
}
void itoa(int n, char* des)
{
if(n 0)
{
int x = (int)pow(10.0, Digit(n)-1);
*des = n / x + ‘0’;
itoa(n-(n/x)*x, des+1);
}
else{
*des = ‘\0’;
}
}
void itora(int n, char* des)
{
*des++ = n 0 ? itora(n/10, des), n % 10 + ‘0’ : ‘\0’;
}
int main()
{
char b[10], c[10];
itoa(12345, b);
itora(12345, c);
printf(“%s %s”, b, c);
}
C語言用遞歸法將一個整數n轉換成字元串的程序中 putchar(n%10+’0′);有什麼作用?
作用就是輸出整數n的個位數對應的字元。
n%10對10取餘數,得到個位。
個位+ ‘0’就是得到對應的數字字元比如1 + ‘0’ = ‘1’
查看下ASCII碼錶就知道了。
C語言,請問:遞歸函數把整數轉換成字元串:如123,字元串「123」怎麼做?非常急
這個題目是用循環好做,用遞歸還有點煩,還好做出來了:
#include “stdio.h”
int itoc(int num, char *buffer)
{
int i=0;
if(num0)
{
*buffer=’-‘;
num=0-num;
itoc(num,buffer+1);
}
else if(num=10)
{
i=itoc(num/10,buffer);
*(buffer+i)=(num%10)+’0′;
*(buffer+i+1)=0;
}
else
{
*buffer=num+’0′;
*(buffer+1)=0;
}
return i+1;
}
void main()
{
char str[20];
itoc(0,str);
printf(“%s\n”,str);
itoc(17858,str);
printf(“%s\n”,str);
itoc(-12345,str);
printf(“%s\n”,str);
}
用遞歸將一個整數n轉換成一個字元串。如將1234轉換為”1234″。
#include “stdio.h”
main()
{
void convert()
int m;
printf(“pinput m=”)
scanf(“%d”,m)
convert(m);
}
void convert(int n)
{
int i;
char c;
if((i=n/10)!=0)/*結束遞歸調用的條件是i==0*/
convert(i);
c=n%10+’0′
putchar(c);
putchar(‘\t’);
}
1、設m=123,第一次進入convert()方法
if((i=n/10)!=0) //這個時候i =123/10 = 12,因為i!=0,所以進入if
convert(i); 調用convert()
2、第二次進入convert()方法,此時參數帶入的是n=12
if((i=n/10)!=0) //這個時候i =12/10 = 1,因為i!=0,所以進入if
convert(i); 調用convert()
3、第三次進入convert()方法,此時參數帶入的是n=1
if((i=n/10)!=0) //這個時候i =1/10 = 0,所以不進入if,直接執行下面語句
c=n%10+’0′ //c=’1′,這裡的+’0’,是為了讓數字轉換為字元
putchar(c); //輸出1
putchar(‘\t’);
因為這個方法體已經執行完畢,所以跳出這個方法,回到第二次的convert()方法。
4、第二次的convert()方法,因為convert(i); 已經執行完,則執行下面那句
c=n%10+’0′ //c=12%10+’0’=’2′ putchar(c); //輸出2
putchar(‘\t’);
因為這個方法體已經執行完畢,所以跳出這個方法,回到第一次的convert()方法。
5、第一次的convert()方法,因為convert(i); 已經執行完,則執行下面那句
c=n%10+’0′ //c=123%10+’0’=’3′ putchar(c); //輸出3
putchar(‘\t’);
原創文章,作者:JMMB,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/139829.html