一定要注意高精度除法的实现是需要注意在对求解的数组的获取是,是从高位先得到数的,这个过程要模拟真正除法的过程,所以最后这个数组的长度,必须在进行处理高位的0的时候就提前赋予,不然会出问题,此题还算出了r即是余数
#include<iostream>
#include<cstring>
using namespace std;
//减法还需要判断大小,无需carry
struct T {
int d[1000];
int len;
T() {
memset(d,0,sizeof(d));
len = 0;
}
};
T TOint(char a[]) {
T c;
int len = strlen(a);
for(int i = 0; i < len; i++) {
c.d[i] = a[len-1-i] - '0';
}
c.len = len;
return c;
}
T chu(T a,int b,int &temp) {
T ans;//temp为余数,初始为0
for(int i = a.len-1; i >= 0; i--) {
temp = temp * 10 + a.d[i];
if(temp < b) { //不够除
ans.d[i] = 0;
} else {
ans.d[i] = temp / b;
temp = temp % b;
}
}
ans.len = a.len;//最重要的是除数的值是从最高位求,所以只能直接给长度
//不用担心carry、等问题,,都会存到,
//也要考虑多个0位在开始端 模拟除法的过程
while(ans.len >= 2&&ans.d[ans.len - 1]==0) {
ans.len--;
}
return ans;
}
int main() {
int N,M;
char a[1000];
gets(a);
int b;
scanf("%d",&b);
T aa = TOint(a);
int r = 0;
T ans = chu(aa,b,r);
for(int i =ans.len-1; i >=0 ; i--) {
printf("%d",ans.d[i]);
}
printf("\n%d",r);
}