PAT-B 1017. A除以B (20)

傳送門

https://pintia.cn/problem-sets/994805260223102976/problems/994805305181847552

題目

本題要求計(jì)算A/B,其中A是不超過1000位的正整數(shù),B是1位正整數(shù)。你需要輸出商數(shù)Q和余數(shù)R,使得A = B * Q + R成立。
輸入格式:
輸入在1行中依次給出A和B,中間以1空格分隔。
輸出格式:
在1行中依次輸出Q和R,中間以1空格分隔。
輸入樣例:
123456789050987654321 7
輸出樣例:
17636684150141093474 3

分析

這道題就是編寫程序模擬除法的筆算方法,輸出時要考慮第1位是0的情況,因?yàn)槌龜?shù)只有1位,所以,只要考慮商的第1位是0的情況即可。

源代碼

//C/C++實(shí)現(xiàn)
#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; //余數(shù)
    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;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容