|

楼主 |
发表于 2013-7-18 03:50:30
|
显示全部楼层
本帖最后由 aleiluya 于 2013-7-18 03:51 编辑
哈哈,首先谢谢大家的积极回答,今天准备进行练习3-6的时候看到itob,就想回去看看以前的练习就去看了已经完成的3-4,正如同我所说的数组的第一个就是地址,传输数组时就是在传送地址,所以根本不需要return,因为在修改被调用函数数组时就是在修改调用函数数组所以:- /*
- 编写函数itob(n,s,b),将整数n转换为以b为低的数,并将转换结果以字符的形式保存到字符串s中。例如,itob(n,s,16)把整数n格式化成十六进制整数保存在s中。
- */
- #include <stdio.h>
- char hex(int n, char s[]);
- char itob(int n, char s[], int b);
- char binary(int n, char s[]);
- void main()
- {
- int n, b;
- static char s[50];
- printf("请安以下的格式输入:你想要转换的数 以什么形式(只限二进制和十六进制)\n");
- while (1)
- {
- scanf("%d %d", &n, &b);
- if ((b == 2) || (b == 16))
- {
- itob(n, s, b); //只需要调用,不需要return。
- printf("%s\n", s); //函数的调用就是在修改数组。
- }
- else
- {
- printf("输入的格式错误,请重新输入!\n");
- }
- }
- }
- /******************************************************/
- char itob(int n, char s[], int b) //本问题函数
- {
- switch (b)
- {
- case 2:
- binary(n, s); //只需要调用,不需要return。
-
- break;
- case 16:
- hex(n, s); //只需要调用,不需要return。
- break;
- }
- }
- /******************************************************/
- char binary(int n, char s[])
- {
- unsigned int i, temp; // 声明为无符号是因为不能是负数。
- temp = ~0; // 求得在任何机器上最大有多少位,并把结果保存在temp。
- for (i = 0; temp > 0; i++)
- {
- temp >>= 1; // 每循环右移一次就把次数保存在i。
- }
- i--; // 减去本身的次数。
- for (temp = 1; i > 0; i--) // 把最高位弄成1,其余0。
- {
- temp <<= 1;
- }
- i = 0;
- while (temp > 0) // 用位操作把n以二进制形式提取出来。
- {
- if ((n & temp) == 0)
- {
- s[i++] = '0';
- }
- else
- {
- s[i++] = '1';
- }
- temp >>= 1; // 每输出一次就右移一位,进行下一位输出准备。
- }
- s[i] = '\0';
- }
- // / /// /// /// /// /// /// /// /// /// /// /// ///
- char hex(int n, char s[])
- {
- unsigned int i, j, temp; // 声明为无符号是因为不能是负数。
- s[0] = '0';
- s[1] = 'X';
- temp = ~0; // 求得在任何机器上最大有多少位,并把结果保存在temp。
- for (i = 0; temp > 0; i++)
- {
- temp >>= 1; // 每循环右移一次就把次数保存在i。
- }
- i /= 4;
- i--;
- for (temp = 15; i > 0; i--) // 把最高位弄成1,其余0。
- {
- temp <<= 4;
- }
- i = 2;
- while (temp) // 第一个循环把左边的空白位删除。
- {
- if (n & temp) // 判断是否是n变量的最高位。
- {
- while (temp) // 第二个循环取值。
- {
- j = n & temp;
- while (((j & 15) == 0) && j) // 如果j不是0就把数字右移到最右边。
- {
- j >>= 4;
- }
- if (j > 9) // 大于9以上的用字母保存。
- {
- s[i++] = (j - 10) + 'A';
- }
- else
- {
- s[i++] = j + '0';
- }
- temp >>= 4; // 每循环一次就右移为下次做准备。
- }
- }
- s[i++] = '0'; // 不是数值的最高位就补0。
- temp >>= 4; // 每循环一次就右移为下次做准备。
- }
- s[--i] = '\0'; // 字符串结束标志。--是为了覆盖掉循环的0。
-
- }
复制代码
|
|