Bigint +运营商
问题描述:
我正在做一个bigint项目,我很难理解为什么我的加法运算符在测试用例上无法正常工作。Bigint +运营商
我排除.h文件,因为它可能不必要。
bigint.cpp#include "bigint.h"
#include<iostream>
#include<fstream>
#include<cstdlib>
#include<cassert>
bigint::bigint()
{ //Default constructor that sets digit to ZERO
for (int i = 0; i < MAX; i++)
{
digits[i] = 0;
}
}
bigint::bigint(int n)
{
for(int i = 0; i < MAX; ++i) //Sets the digit to ZERO
digits[i] = 0;
for (int i = 0; n != 0 ; ++i)
{
digits[i] = (n % 10); //
n = n/10;
}
}
bigint::bigint(const char new_digits[])
{
int null = 0;
int temp = 0;
for(int i = 0; i < MAX; ++i)
{
digits[i] = 0;
}
while(new_digits[null] != '\0')
++null;
--null;
temp = null;
for(int j = 0; j < MAX && temp >= 0; ++j)
{
digits[j] = new_digits[temp] - '0';
temp -= 1;
}
}
bool bigint::operator==(const bigint& equal) const
{
int i = 0;
while(i < MAX)
{
if(digits[i] != equal.digits[i])
{
return false;
}
++i;
}
return true;
}
std::ostream& operator<<(std::ostream& output, const bigint& source)
{
int sub1 = MAX - 1; //subtracts 1 from the maximum size
while(source.digits[sub1] == 0)
{
--sub1; //EMPTY
}
while(sub1 > -1)
{
output << source.digits[sub1];
--sub1;
}
std::cout << std:: endl;
return output;
}
std::istream& operator>>(std::istream& in, bigint& source)
{
char getdata[MAX];
char user_input;
int i = 0;
in.get(user_input);
while(!in.eof() && user_input != ';')
{
in.get(user_input);
source.digits[i] = user_input;
++i;
}
source = bigint(getdata);
return in;
}
char bigint::operator[](const int i)
{
return digits[i];
}
bigint bigint::operator+(const bigint rhs)
{
bigint result;
int i = 0;
for(; i < MAX; ++i)
{
if((digits[i] + rhs.digits[i]) > 9)
{
digits[i+1] = digits[i+1] + 1 ;
}
result.digits[i] = (digits[i] + rhs.digits[i]);
result.digits[i] = result.digits[i] % 10;
}
return result;
}
Main.cpp的(试验情况)
int main()
{
// Setup fixture
bigint left("1");
bigint right("9");
bigint result;
// Test
result = (left + right);
Verify
assert(left == "1");
assert(right == "9");
assert(result == "10");
}
在该测试情况下,程序中止于断言(结果== “10”);
但是如果我有相同的测试用例,除了assert(result == 10);程序运行的 。
任何人都可以说为什么?
答
首先,您应该实施bigint::operator=(const bigint&)
,赋值运算符。
现在,在operator+
,你改变了左侧对象的内容,在此代码:
if((digits[i] + rhs.digits[i]) > 9)
{
digits[i+1] = digits[i+1] + 1 ;
}
这不是很好。例如,如果你运行此代码:
bigint x("5");
bigint y("6");
x+y;
x+y;
你最终会与x
是17
接下来,你被值传递为bigint::operator
参数,你也许应该通过传参考(&
)。
最后,在这里你的缩进积极恶意:
while(new_digits[null] != '\0')
++null;
--null;
什么是循环体吗?没错,不是第三条线。请不要像这样缩进代码,它会让小猫哭泣。编程小猫,至少。
注意:这里没有看到任何动态内存分配代码,这意味着digits
可能是一个静态大小的数组。如果你打算这么做的话,确保它足够大,并且要知道如果超过它的尺寸就会破坏它。
+0
对于任何不相信编程小猫的人:http://www.elistmania.com/images/articles/117/Original/LOLCODE.jpg – 2012-02-06 02:16:21
如何格式化您的代码? – ObscureRobot 2012-02-06 01:49:44
您正在测试一次。为比较运算符,加法和'bigint(char [])'构造函数分别进行测试。 – 2012-02-06 01:57:24