天天看點

1022 D進制的A+B (20 分)-PAT乙級真題

輸入兩個非負 10 進制整數 A 和 B (≤2​30​​ −1),輸出 A+B 的 D (1<D≤10)進制數。輸入格式:

輸入在一行中依次給出 3 個整數 A、B 和 D。

輸出格式:

輸出 A+B 的 D 進制數。

輸入樣例:

123 456 8

輸出樣例:

1103

#include <cstdio>
using namespace std;
int main(){
    int a=0,b=0,c;
    int result[31]={0},count=0; 
    if(scanf("%d%d%d",&a,&b,&c)==3);
    int sum=a+b;
    do{
        result[count++]=sum%c;
        sum/=c;
    }while(sum!=0);
    for(int i=count-1;i>=0;i--){  //從高位到低位輸出
        printf("%d",result[i]);
    }
    return 0;
}
           

注意事項:

使用do…while()形式使十進制數恰好為0執行一次循環體。

從高位到低位輸出,result[count]=0時sum為0,退出循環,count-1為最高位。