#include <stdio.h> #include <string.h> int a[20]; int b[20]; //将十进制数转化成 base进制 void baseConvert(int num,int * array,int base) { int i = 0; while(num) { array[i] = num % base; num = num / base; i++; } } void basePrint(int * arr) { int i = 0; while(arr[i] != -1) i++; for(i=i-1;i>-1;i--) printf("%d",arr[i]); } void calculate(int base,int x,int y) { baseConvert(x,a,base); baseConvert(y,b,base); int k = 0; //这个是进位 int i = 0; int res[20]; //int res[20] = {-1}; 这种初始化不管用 memset(res,-1,sizeof(res)); while( a[i] != -1 && b[i] != -1) { res[i] = a[i] + b[i] + k; k = 0;//用过的进位马上清零 if(res[i] >= base) { k = res[i] / base; res[i] = res[i] % base; } i++; } if(a[i] == -1) { while(b[i] != -1) { res[i] = b[i] + k; k = 0; if(res[i] >= base) { res[i + 1] = res[i] / base; res[i] = res[i] % base; } i++; } } if(b[i] == -1) { while(a[i] != -1) { res[i] = a[i] + k; k = 0; //此处千万记住,用过的进位 一定要清零!!!!!! if(res[i] >= base) { k = res[i] / base; res[i] = res[i] % base; } i++; } if( k!= 0) res[i] = k; } basePrint(a); printf(" + "); basePrint(b); printf(" = "); basePrint(res); printf("\n"); } int main() { int base,x,y; memset(a,-1,sizeof(a)); memset(b,-1,sizeof(b)); //while(scanf("%d %d %d",&base,&x,&y),base,x,y) 如果加上 \n 则要输入四个0 才会停止??? while(scanf("%d %d %d",&base,&x,&y),base,x,y) { calculate(base,x,y); memset(a,-1,sizeof(a)); memset(b,-1,sizeof(b)); } return 0; }
如果将那个baseConvert函数修改,则下面的计算将更简单
int baseConvert(int num,int * array,int base) { int i = 0; while(num) { array[i] = num % base; num = num / base; i++; } return i--; }