PAT Basic 1017. A除以B (20)(C語言實現)
阿新 • • 發佈:2019-02-15
, CSDN內容暫時不更新(將來有計劃更新), 請前往連結檢視最新內容. 歡迎star 我的repo
題目本題要求計算A/B,其中A是不超過1000位的正整數,B是1位正整數。你需要輸出商數Q和餘數R,使得A = B * Q + R成立。
輸入格式:
輸入在1行中依次給出A和B,中間以1空格分隔。
輸出格式:
在1行中依次輸出Q和R,中間以1空格分隔。
輸入樣例:
123456789050987654321 7
輸出樣例:
17636684150141093474 3
思路
就是模擬一個手算除法的過程。
程式碼
#include <stdio.h> int main() { int B; char A[1001], *p = A; scanf("%s %d", A, &B); /* read 2 digits from highest digit of A, do manual division, get the quotient and remainder. Read one more digit, combine this with the last remainder to get a new 2-digits number. Do this until read to the end of A */ /* the results are stored in A and B instead of printed out on-the-fly */ int twodigit, remainder = 0; for(int i = 0; A[i]; i ++) { twodigit = remainder * 10 + (A[i] - '0'); A[i] = twodigit / B + '0'; remainder = twodigit % B; } B = remainder; /* print */ if(A[0] == '0' && A[1] != '\0') p++; printf("%s %d", p, B); return 0; }