PAT-A除以B

版权声明:一只努力变强的编程汪,欢迎交流! https://blog.csdn.net/qq_42020563/article/details/81532718

A除以B (20)

  •  
  •  
  •  
  •  

时间限制 1000 ms 内存限制 32768 KB 代码长度限制 100 KB 判断程序 Standard (来自 小小)

题目描述

本题要求计算A/B,其中A是不超过1000位的正整数,B是1位正整数。你需要输出商数Q和余数R,使得A = B * Q + R成立。

输入描述:

输入在1行中依次给出A和B,中间以1空格分隔。


 

输出描述:

在1行中依次输出Q和R,中间以1空格分隔。

输入例子:

123456789050987654321 7

输出例子:

17636684150141093474 3

 不能用通常的A/B,A%B算商和余数,因为A,B可能非常大,会导致浮点错误。

#include<iostream>
#include<string>
using namespace std;
int main()
{
	string A, Q;
	int B,R=0;
	cin >> A >> B;
	int length = A.length();
	int temp = A[0] - '0';
	if (temp >= B)
		Q.push_back(temp / B + '0');
	for (int i = 1; i < length; i++)
	{
		R = temp%B;
		temp = R * 10 + A[i] - '0';
		Q.push_back(temp / B + '0');
	}
	R = temp%B;
	if (length == 1 && A[0] - '0' < B)
		cout << "0 " << A[0] - '0';
	else
	cout << Q << " " << R;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42020563/article/details/81532718