+ =运算符的问题 [英] problem with the += operator

查看:83
本文介绍了+ =运算符的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream>
#include <string>
#include <vector>
using namespace std;

class Mint {
public:

	Mint();
	Mint(int);
	Mint (const char  *s);
	string afficher();
	Mint operator+=(const Mint &rhs); //returns mint + rhs
private:
	vector<char> num;
};
#include "Mint.h"
#include <string.h>

Mint::Mint()
{
	num.push_back(0);
}
Mint::Mint(int n)
{
	while(n!=0)
	{
		num.push_back(n%10);
		n = n/10;
	}
}
Mint::Mint(const char* s)
{
		int i = 0 ;
		for(i=strlen(s)-1;i>=0;i--)
		num.push_back(s[i] - '0');
}
string Mint::afficher(){
	string s="";
	int i;
	for(i=num.size()-1;i>=0;i--)
		s += char('0'+num[i]);
	return s;
}
Mint Mint::operator+=(const Mint &rhs){
	int len = num.size();
	int carry = 0;
	if(len < rhs.num.size())
	{
		len = rhs.num.size();
	}
	int i;
	for (i=0;i>=len-1;i++)
	{
		num.push_back((num[i]+rhs.num[i]+carry)%10);
		carry =(num[i]+rhs.num[i]+carry) / 10;
	}
	return *this;

}
#include "Mint.h"
#include <iostream>
#include <string>
using namespace std;



int main()
{
	Mint x,z;
	Mint a = "655478461469974272005572";
	Mint b = "8";
	a += b;
	cout << a.afficher()<<endl;

}





hii伙计们请查看代码并告诉我+ =运算符有什么问题因为我得到一些奇怪的结果;



hii guys please check out the code and tell me what is wrong with the += operator because i get some strange results;

推荐答案

有多个问题。最明显的是你的循环永远不会进入。你需要改变你的大于小于。



下一个问题是你需要将len变量设置为较小的向量大小(改变较少)而不是大于)。否则当循环越界时你会得到一个异常。



第三个问题是你把计算结果推到了num矢量 - 你需要取代指数值,而不是附加到已存在的指数值。



最后一个,除非你开始在两边使用更大的数字,否则不会变得明显方程式,你需要在循环存在后检查进位,如果有值,则将其添加到结果中。



There is more than one problem. The most obvious is that your loop will never get entered. You need to change your greater than to a less than).

The next problem is that you need to set the len variable to the smaller vector size (change the less than to a greater than). Otherwise you will get an exception when the loop goes out of bounds.

Third problem is that you are pushing the result of the calculation into the num vector - you need to be replacing the index value, rather than appending to what is already there.

The last, which will not become evident unless you start using bigger numbers on both side of the equation, is that you need to check the carry after the loop exists, and if it has a value, add it to the result.

Mint Mint::operator+=(const Mint &rhs) {
	size_t len = num.size();
	char carry = 0;

	if (len > rhs.num.size())
		len = rhs.num.size();

	size_t i;
	for (i = 0; i <= len - 1; i++)
	{
		char result = num[i] + rhs.num[i] + carry;
		num[i] = result % 10;
		carry = result / 10;
	}

	while (carry)
	{
		if (i < num.size()) 
		{
			num[i] += carry;
			if (num[i] >= 10)
			{
				num[i] -= 10;
				i++;
			}
			else
				carry = 0;
		}
		else {
			num.push_back(carry);
			carry = 0;
		}
	}
	return *this;
}


这篇关于+ =运算符的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆