C程序设计(第二版 新版)第三章 习题

1. 函数expand(s1,s2),将字符串s1中类似a-z的字符串在s2中扩展为等价abc...xyz完整序列

#include<stdio.h>
void expand(char s1[], char s2[])
{
     char c;
     int i, j;
     
     i = j = 0;
     while( (c = s1[i++]) != '\0')
     {
            if( s1[i] == '-' && s1[i+1] >= c)
            {
                i++;
                while( c < s1[i])
                   s2[j++] = c++;
            }
            else
                s2[j++] = c;       
     }
     s2[j] = '\0';
}
int main()
{
    char s1[20],s2[100];
    scanf("%s%*c",s1);
    expand(s1,s2);
    printf("string = %s", s2);
    getchar();
    return 1;
}


2. itoa(n,s)函数的改进,一般我们编的不能处理n为负数最大值的情况,一下是函数的改进与对比(3-4)

#include<stdio.h>
#include<string.h>
#include<limits.h>
#define abx(x) ((x) < 0 ? -(x):(x))
void reverse(char s[])
{
     int c, i, j;
     
     for( i = 0, j = strlen(s) - 1; i < j; i++, j--)
     {
          c = s[i];
          s[i] = s[j];
          s[j] = c;
     }
}
void itoa1(int n, char s[])
{
     int i, sign;
     
     i = 0;
     if( (sign = n) < 0)
         n = -n; //当n为负数最大数是不成立的,因为整数的最大数字 =  | 负数最大值| -1
     do
     {
         s[i++] = n % 10 + '0';
     }while( (n /= 10) > 0);
     if(sign < 0)
             s[i++] = '-';
     s[i] = '\0';
     reverse(s);
}
void itoa2(int n, char s[])
{
     int i, sign;
     
     i = 0;
     sign = n;
     do
     {
         s[i++] = abs(n % 10) + '0';
     }while( (n /= 10) != 0);
     if(sign < 0)
             s[i++] =  '-';
     s[i] = '\0';
     reverse(s);
}
int main()
{
    char s[20];
    int n = INT_MIN;
    itoa1(n,s);
    printf("s1 = %s\n",s);
    itoa2(n,s);
    printf("s2 = %s\n",s);
    getchar();
    return 1;
} 


3. 函数itob(n,s,b)是把n的b进制表示以字符串的形式存储在s中(3-5)

#include<stdio.h>
#include<limits.h>
#include<string.h>
#define abx(x) ((x) < 0 ? -(x):(x))
void inverse(char s[])
{
     int i,  j,  c;
     
     for(i = 0, j= strlen(s) - 1; i < j; i++,j--)
     {
             c = s[i];
             s[i] = s[j];
             s[j] = c;
     }
}
void itob(int n, char s[], int b)
{
     int i, j, sign;
     
     i = 0;
     sign = n;
     do
     {
          j = abs(n % b);
          s[i++] = ( j <= 9) ? j + '0' : j + 'a' - 10;
     }while( (n /= b) != 0);
     if(sign < 0)
         s[i++] = '-';
     s[i] = '\0';
     inverse(s);
}
int main()
{
    int n;
    char s[20];
    n = INT_MIN;
    itob(n, s, 16);
    printf("result = %s\n", s);
    getchar();
    return 1;   
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值