【问题描述】
编写一函数int comb(int a,int b),将两个两位数的正整数a、b合并形成一个整数并返回。合并的方式是:将a的十位和个位数依次放在结果的十位和千位上, b的十位和个位数依次放在结果的个位和百位上。例如,当a=45,b=12。调用该函数后,返回5241。要求在main函数中调用该函数进行验证:从键盘输入两个整数,然后调用该函数进行合并,并输出合并后的结果。
【输入形式】
输入两个两位数的正整数,以空格隔开。
【输出形式】
输出合并后的正整数。
【输入样例】
45 12
【输出样例】
5241
--------------------------------
个人代码:
#include <stdio.h> int comb(int a, int b){ int res,m[2],n[2]; m[0] = a%10;//个位 m[1] = a/10;//十位 n[0] = b%10;//个位 n[1] = b/10;//十位 res = m[0]*1000+n[0]*100+m[1]*10+n[1]; return res; } int main(){ int a,b,res; scanf("%d %d",&a,&b); res = comb(a,b); printf("%d\n",res); getchar(); return 0; }
标答:
#include <stdio.h> #include <stdlib.h> int combine(int a, int b); main() { int a,b; scanf("%d %d", &a, &b); printf("%d\n",combine(a, b)); } int combine(int m, int n) { int s[2], t[2], i = 0, j = 0; char st[5]; do{ s[i++] = m % 10; t[j++] = n % 10; }while((m /= 10)*(n /= 10) > 0); st[0] = s[0] + '0'; st[1] = t[0] + '0'; st[2] = s[1] + '0'; st[3] = t[1] + '0'; st[4] = '\0'; return atoi(st); }
---------------------------
1、获取某整数的各位值也可用atoi()函数实现:
头文件<stdlib.h>
int i = 0; char s[16]; do { s[i++] = x % 10 + '0'; } while ((x /= 10) > 0); s[i]='\0'; x = atoi( s );
字符串s[]最后一个的值必须为'\0',因为atoi()函数是将字符串转换为int型,以'\0'为标志结束字符串。