バイナリ変換ステップは:
バイナリ変換に進P-Qは、2段階を必要とします
- Pの数は十進数の16進数に変換されます。
- Q進の小数変換
int y =0,product=1;//p进制x转化为10进制的y
while(x!=0){
y=y+(x%10)*product;//x%10为了取x的个位数
x=x/10;
product=product*p;
}
//十进制y转化为Q进制z
int z[40],num=0;//数组z存放Q的进制数y的每一位,num为位数
do{
z[num++] = y%Q;//除基取余
y=y/Q;
}while(y!=0);
//这样数组从高位z[num-1]到低位num[0]就正好是Q进制的z。
//这儿用do while而不用while是因为如果y正好为0,用while会让循环直接跳出,结果出错。
タイトル:PAT 1022 D六角A + B(20分)
二つの非負小数点整数A及びB(≤230 -1)、D(1 <D≤10)進数の出力A + Bを入力してください。
入力フォーマット:
指定された整数入力逐次3行で、BおよびD.
出力フォーマット:
進数の出力A + D B。
サンプル入力:
123 456 8
出力例:
1103
回答:
//一刷代码
#include <iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
int main() {
long long int a,b,c;
int d;
cin>>a>>b>>d;
c = a+b;
int v[100];
int i = 0;
if(c==0){
cout<<"0";
return 0;
}
while(c!=0){//有一个测试点通不过,因为少考虑了c = 0的情况
v[i] = c%d;
c = c/d;
i++;
}
for(int j = i-1;j>=0;j--){
cout<<v[j];
}
return 0;
}
//整理思路后的代码
#include<iostream>
using namespace std;
int main(){
int a,b,c;
cin>>a>>b>>c;
a=a+b;
int z[40],num=0;//z里面存放c进制数的每一位,num表示位数。
do{
z[num++]=a%c;
a/=c;
}while(a!=0);
for(int i = num-1;i>=0;i--)//逆序输出就是结果
cout<<z[i];
return 0;
}