本题要求计算 A/B,其中 A
是不超过 1000 位
的正整数,B
是 1 位正整数
。你需要输出商数 Q 和余数 R,使得 A=B×Q+R
成立。
输入格式:
输入在一行中依次给出 A
和 B
,中间以 1 空格
分隔。
输出格式:
在一行中依次输出 Q
和 R
,中间以 1 空格
分隔。
输入样例:
123456789050987654321 7
输出样例:
17636684150141093474 3
代码:
#include<iostream>
#include<cstring>
using namespace std;
char a[1001]={};
//作为全局变量,省去将这几个数和数组传入函数的麻烦
int b,lena;
struct num{
int len,yu;
char itself[1001];
num(){
//这是构造函数,初始化全为0,具体见《谭浩强C++》构造函数那一章节
yu=0;//余数初始化为0
len=0;//长度初始化为0
memset(itself,0,1001); //初始化数组里面的字符全为0
}
};
num reverse(char a[]){//将字符串的顺序逆转
num temp;
temp.len=strlen(a);
for(int i=0;i<lena;i++){
temp.itself[lena-i-1]=a[i]-'0';
//这里一定要记住是要减去'0',因为我们用的是字符
}
return temp;
}
num division(num a){//除法函数
num temp;
temp.len =a.len ;
for(int i=lena-1;i>=0;i--){
temp.yu =a.itself [i]+temp.yu*10;
if(temp.yu <b)//如果被除数的某一位不够
temp.itself [i]=0;
else//如果够
temp.itself [i]=temp.yu/b;//算上之前的余数
temp.yu =temp.yu%b;//余数刷新
}
for(int i=lena-1;i>=0;i--){//去掉最后面的0
if(temp.itself [i]==0){
temp.len--;
}
else {
break;
}
}
//------------------------------------------------
//这是算法笔记里面的去掉后面的0的函数,稍微有点难记忆
// while(temp.itself [temp.len -1]==0&&temp.len -1>=0){
// temp.len --;
// }
//------------------------------------------------
return temp;
}
int main(){
scanf("%s %d",a,&b);
num newnum;
lena=strlen(a);
newnum=reverse(a);
newnum=division(newnum);
if(newnum.len ==0){//没有这个会有一个测试点无法通过
printf("0");
}
else{
for(int i=newnum.len -1;i>=0;i--){
printf("%d",newnum.itself [i]);
} //输出除法的结果
}
printf(" %d",newnum.yu );
return 0;
}