C程序设计语言习题(3-5)

编写函数itob(n,s,b),将整数n转换为以b为底的数,并将转换结果以字符的形式保存到字符串s中。e.g.itob(n,s,16)把整数n格式化为十六进制整数保存在s中。

 1 #include<stdio.h>
 2 #include<ctype.h>
 3 #include<string.h>
 4 
 5 void swap(char *a, char *b)
 6 {
 7     int t;
 8     t = *a;
 9     *a = *b;
10     *b = t;
11 }
12 
13 void reverse(char *s)  //倒置串s
14 {
15     int c, i, j;
16     i = 0;
17     j = strlen(s) - 1;
18     while(i < j) {
19         swap(&s[i], &s[j]);
20         i++;
21         j--;
22     }
23 }
24 
25 void itob(int n, char *s, int b)
26 {
27     int i, j, sign;
28     i = 0;
29     if((sign = n) < 0)
30          n = -n;
31     do {
32         j = n % b;
33         s[i++] = (j <= 9) ? j + '0' : j - 10 + 'A';
34     } while((n /= b) > 0);
35     if(sign < 0)  s[i++] = '-';
36     s[i] = '\0';
37     reverse(s);
38 }
39 
40 int main()
41 {
42     char a[1000];
43     int n, b;
44     n = 1232323;
45     b = 16;
46     itob(n,a,b);
47     printf("%s\n",a);
48     return 0;
49 }

 

转载于:https://www.cnblogs.com/cpoint/p/3367505.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值