C++ 1017 A除以B(20 分)

问题:大数除法

思路:从第一位数字开始计算,就像在草稿本上计算除法一样。

#include <iostream>
#include <string> 
using namespace std;
int main()
{
	string a;
	int b;
	cin >> a >> b;
	int t, temp;
	int lena = a.length();
	t = (a[0] - '0') / b;  //商 
	if (lena == 1 || (t != 0 && lena > 1)) { //分为长度为1或大于1两种情况 
	 	cout << t;
	}
	temp = (a[0] - '0') % b; //余数 
	for (int i = 1; i < lena; i++) {
		t = ((temp * 10) + a[i] - '0') / b;
			cout << t;
		temp = ((temp * 10) + a[i] - '0') % b;
	} 
	cout << " " << temp;
	return 0;
}

注意点:

1 注意1234/7   这种情况,第一位除了为0,此时不能写上;

2 注意1/7   这种情况,虽然第一位为0,但需要写上。

代码2(自写)

#include <iostream>
#include <string> 
using namespace std;
int main()
{
	string a;
	int b;
	cin >> a >> b;
	int t, temp;
	int lena = a.length();
  t=(a[0]-'0')/b;
  if(t!=0) cout<<t;             //考虑11/7  开头的0不需要写出来的情况
  if(t==0&&lena==1) cout<<0;   //考虑1/7  商为0   此时0需要写出来的情况
  temp=(a[0]-'0')%b;
  for(int i=1;i<lena;i++){
    t=(temp*10+(a[i]-'0'))/b;
    cout<<t;
    temp=(temp*10+(a[i]-'0'))%b;
  }
  cout<<" "<<temp;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_36122764/article/details/82114055