傳送門
https://pintia.cn/problem-sets/994805260223102976/problems/994805305181847552
題目
本題要求計算A/B,其中A是不超過1000位的正整數,B是1位正整數。你需要輸出商數Q和余數R,使得A = B * Q + R成立。
輸入格式:
輸入在1行中依次給出A和B,中間以1空格分隔。
輸出格式:
在1行中依次輸出Q和R,中間以1空格分隔。
輸入樣例:
123456789050987654321 7
輸出樣例:
17636684150141093474 3
分析
這道題就是編寫程序模擬除法的筆算方法,輸出時要考慮第1位是0的情況,因為除數只有1位,所以,只要考慮商的第1位是0的情況即可。
源代碼
//C/C++實現
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
int main()
{
char a[1000];
int b;
scanf("%s %d", a, &b);
char quotient[1000]; //商
int rest = 0; //余數
for(int i = 0; i != strlen(a); i++){
quotient[i] = ((rest * 10 + a[i] - 48) / b) + 48;
rest = (rest * 10 + (a[i] - 48)) % b;
}
if(quotient[0] == '0' && quotient[1] != 0){
printf("%s", quotient + 1);
}
else{
printf("%s", quotient);
}
printf(" %d\n", rest);
return 0;
}