适合初步练习PAT乙级——(1017) A除以B
本题要求计算 A/B,其中 A 是不超过 1000 位的正整数,B 是 1 位正整数。你需要输出商数 Q 和余数 R,使得 A=B×Q+R 成立。
输入格式:
输入在一行中依次给出 A 和 B,中间以 1 空格分隔。
输出格式:
在一行中依次输出 Q 和 R,中间以 1 空格分隔。
输入样例:
123456789050987654321 7
输出样例:
17636684150141093474 3
#include<iostream>
#include<string>
using namespace std;
int main() {
string s;
int a, t,temp=0;
cin >> s >> a;
t = (s[0] - '0') / a;
if (t!= 0||s.length()==1)cout << t;//要注意为被除数只为一位的情况
temp = (s[0] - '0') % a;
for (int i = 1; i < s.length(); i++) {
t = (temp * 10 + s[i] - '0') / a;
cout << t;
temp = (temp * 10 + s[i] - '0') % a;
}
cout << " " << temp;
return 0;
}
思路:模拟手动除法的过程,每次用第一位取除以B,如果得到的商不是0就输出,否则就*10+下一位,直到最后的数为余数。
更清楚的分类:
1.被除数为1位
2.被除数的首位大于除数
3.被除数的首位小于等于除数
#include<iostream>
#include<string>
using namespace std;
int main() {
string s;
int a,temp,yushu,sum;
cin >> s >> a;
sum = s[0] - '0';
for (int i = 0; i < s.length(); i++) {
temp = sum / a;
if (i ==0&&s.length()==1)cout << temp;//当除数为1位
//当被除数第一位小于除数
else if (sum < a) {
if(i!=0)cout << temp;//不为输出首位0
}
//当被除数第一位大于等于除数
else cout << temp;
yushu = sum % a;
sum = yushu*10+(s[i+1]-'0');
}
cout << " " << yushu;
return 0;
}