Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2538958
  • 博文数量: 308
  • 博客积分: 5547
  • 博客等级: 大校
  • 技术积分: 3782
  • 用 户 组: 普通用户
  • 注册时间: 2009-11-24 09:47
个人简介

hello world.

文章分类

全部博文(308)

分类: C/C++

2010-08-11 17:01:30

   用递归法将一个整数n转化成字符串。例如,输入483,应输出字符串"483".n的位数不确定,可以是任意位数的整数。
   习题答案上有用递归操作的函数,不过我看不太懂。看来要慢慢的去阅读源代码了。我自己写了一个函数convert1(int)。此函数的原理是进行求余操作,然后将求余结果存在数组中,然后将数组翻转操作,即可得到我们想要的效果。代码如下:
 

#include <stdio.h>

void convert1(int);
char int2char(int);
void inverse(char[]);
void convert(int); //书上编写的函数,不过我分析的还有些迷糊。

int main(int argc, char *argv[])
{
    int number;
    printf("please input a number:");
    scanf("%d",&number);
    convert1(number); //调用我写的函数,虽然复杂,还算能使用,书上要求用递归,这点我没有做到。

    system("pause");
    return 0;
}

void convert1(int n)
{
     char ch[10];
     int m = 0;
     int i = n,j,k;
     do
     {
       j = i % 10;
       ch[m++] = int2char(j);
       i = (i - j) / 10;
     }while (i);
     ch[m] = '\0';
     inverse(ch); //begin inverse.

     puts(ch);
}

char int2char(int n)
{
     char c;
     if (n >= 0 && n <= 9)
     {
        switch (n)
        {
               case 0:
                    c = '0';
                    break;
               case 1:
                    c = '1';
                    break;
               case 2:
                    c = '2';
                    break;
               case 3:
                    c = '3';
                    break;
               case 4:
                    c = '4';
                    break;
               case 5:
                    c = '5';
                    break;
               case 6:
                    c = '6';
                    break;
               case 7:
                    c = '7';
                    break;
               case 8:
                    c = '8';
                    break;
               case 9:
                    c = '9';
                    break;
        }
     }
     else
     {
         c = ' ';
     }
     return c;
}

void inverse(char ch[])
{
     int begin = 0, end = strlen(ch) - 1, mid = end / 2;
     char c;
     do
     {
        c = ch[begin];
        ch[begin ++] = ch[end];
        ch[end --] = c;
     }while (begin < mid);
}

void convert(int n)
{
     int i;
     if ((i = n / 10) != 0)
     {
        convert(i);
     }
     putchar(n % 10 + '0');
}


阅读(2242) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~