1017 A除以B(C++)

发布时间 2023-05-26 22:13:53作者: 轻挼草色

一、问题描述:

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

输入格式:

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

输出格式:

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

输入样例:

123456789050987654321 7

输出样例:

17636684150141093474 3

二、代码实现:

 1 #include <iostream>
 2 #include <cstring>
 3 using namespace std;
 4 int main()
 5 {
 6     char a[1001];
 7     int str[1000]={0};//Q
 8     int b;
 9     cin>>a>>b;
10     int n=0,j=0;
11     int yu;//R
12     if(a[0]=='0')//被除数为0
13     {
14         cout<<"0"<<" "<<"0"<<endl;
15         return 0;
16     }
17     if(b==0)//除数为0
18     {
19         cout<<"0"<<" "<<a<<endl;
20         return 0;
21     }
22     for(int i=0;i<strlen(a);i++)
23     {
24         n=n*10+(a[i]-'0');
25         if(n>=b)
26         {
27             str[j++]=n/b;
28             n=n%b;
29             yu=n;
30         }
31         else if(n<b)
32         {
33             if(str[0]!=0)
34             {
35                 str[j++]=0;
36             }
37             else if(strlen(a)==1)//被除数为一位数,除数小于被除数
38             {
39                 yu=n;
40                 str[j++]=0;
41             }
42         }
43     }
44     for(int i=0;i<j;i++)
45     {
46         cout<<str[i];
47     }
48     cout<<" "<<yu<<endl;
49     return 0;
50 }