1022 D进制的A+B
输入两个非负10进制整数A和B(<=2^30^-1),输出A+B的D (1 < D <= 10)进制数。
输入格式:
输入在一行中依次给出3个整数A、B和D。
输出格式:
输出A+B的D进制数。
输入样例:
123 456 8
输出样例:
1103
就是进制转换的问题,我之前不知道有短除法,然后去查c/c++有没有进制转换的函数,还真找到一个,就是
itoa()
具体用法,D是任意进制,num是A+B的和,输出num转换后的结果
#include<stdlib.h>
#include<stdio.h>
using namespace std;
int main()
{
int A,B,D;
scanf("%d %d %d",&A,&B,&D);
int num=A+B;
char temp[200];
itoa(num,temp,D);
printf(temp);
}
itoa()函数有3个参数:第一个参数是要转换的数字,第二个参数是要写入转换结果的目标字符串,第三个参数是转移数字时所用的基数。在上例中,转换基数为10。10:十进制;2:二进制…
itoa并不是一个标准的C函数,它是Windows特有的,如果要写跨平台的程序,请用sprintf。
sprintf就是将结果写入到字符串中然后输出
是Windows平台下扩展的,标准库中有sprintf,功能比这个更强,用法跟printf类似:
这样写在本地的编译器能通过,但是提交到OJ就不行了,后面改用短除法
#include<iostream>
#include<stdlib.h>
#include<stdio.h>
using namespace std;
int main()
{
int A,B,D;
scanf("%d %d %d",&A,&B,&D);
int num=A+B;
char temp[1000];
int i=0;
//要对0判断
if ( num == 0 ) {
cout<<"0";
}
while(num)
{
temp[i++]=num%D+'0';
num=num/D;
}
for(int j=i-1;j>=0;j--)
{
cout<<temp[j];
}
}