本题要求计算A/B,其中A是不超过1000位的正整数,B是1位正整数。你需要输出商数Q和余数R,使得A = B * Q + R成立。
输入格式:
输入在1行中依次给出A和B,中间以1空格分隔。
输出格式:
在1行中依次输出Q和R,中间以1空格分隔。
输入样例:
123456789050987654321 7
输出样例:
17636684150141093474 3
思路便是,除法算法的模拟一遍。很容易。但是输出要考虑仔细点。要注意,长数字第一个数字不能是0,且,长数字是一个数的时候,输出为 0 余数
#include<iostream>
#include<string>
using namespace std;
void printf(const string Q, int R)
{
cout << Q << " " << R << endl;
}
int charToInt(char a)
{
return (int)(a - '0');
}
char intToChar(int a)
{
return (char)('0' + a);
}
void fun(const string A,const int B)
{
string Q;
int R,p;
int temp_val=0;
for (int i = 0; i < A.length(); i++)
{
temp_val = (temp_val%B) * 10 + charToInt(A.at(i));
if (temp_val/B||i!=0)
{
Q += intToChar(temp_val / B);
}
else if (A.length()==1)
{
Q += intToChar(temp_val / B);
}
}
cout << Q << " " << temp_val % B<<endl;
}
int main()
{
string A;//被除数h,商
int B;//除数
cin >> A >> B;
fun(A, B);
system("pause");
return 0;
}