运算符==重载

发布于 2024-12-29 17:44:48 字数 1853 浏览 1 评论 0 原文

我正在为学校做一个项目,我需要创建一个 bigint 类,到目前为止它有 4 个要求。

1.) 编写一个方法来编写每行最多打印 80 位数字的 bigint。

2.) 编写一个方法来比较两个 bigint 是否相等。它应该返回一个布尔值。

3.) 编写一个方法将 bigint 初始化为您提供的 int 值 [0, maxint]。

4.) 编写一个方法将 bigint 初始化为 char[]。

我认为我的 2 和 3 是正确的,但我在比较两个 bigint 时遇到了麻烦,我希望有人能引导我走向正确的方向,如何将每行打印限制为 80 位数字。

到目前为止,这是我的代码:

.h 文件

class bigint
{
public:

bigint(); //default constructor

bool operator==(const bigint& num1); 

bigint( int n);

bigint(char new_digits[]);


private:
    int digit[MAX];
    int digitb[MAX];

};

是实现文件:

#include "bigint.h"
#include<cassert>
#include<iostream>


//default constructor
bigint::bigint()
{
     for (int i = 0; i < MAX; i++) 
     {
    digit[i] = 0;
     }

     }


     bigint::bigint( int n )
     {
    int i = 0;



      while(n > 0)
    {
       digit[i] = n % 10;
       n = n /10;
       ++i;
break;
     }


  for(i; i< MAX; ++i)
      digit[i] = 0;


     }

 bool bigint::operator==(const  bigint& num1)
     {

       for(int i = 0; i < MAX; i++)
          {
        if (num1.digit == num1.digit)
              return true;
          }
        return false;

      }


   bigint::bigint(char new_digit[])
      {
     int i = 0;

         //Reads the characters of numbers until it is ended by the null symbol

            while(new_digit[i] != '\0')
             ++i;

             --i;

       //Converts the characters into int values and puts them in the digit array
         while( i >= 0)
    {
            digit[i] = new_digit[i] - '0';
            --i;
    }


}


}



int main()
  {

     #include<iostream>

using namespace std;
using PROJECT_1::bigint;

bigint a(0);

assert(a == 0);
  }

顺便说一句,我并不是想获得一小时前刚开始的​​作业的答案。我一整天都在努力解决这个问题,最后我屈服并寻求帮助。

I'm doing a project for school and where I need to create a bigint class and it has 4 requirements thus far.

1.) Write a method to write a bigint that prints at most 80 digits per line.

2.) Write a method to compare if two bigints are equal. It should return a bool.

3.) Write a method to initialize a bigint to an int value you provide [0, maxint].

4.) Write a method to initialize a bigint to a char[].

I think I have 2 and 3 correct, but I'm having trouble with comparing two bigints and I was hoping that someone could lead me in the right direction on how to limit print to 80 digits per line.

Here's my code so far:

.h file

class bigint
{
public:

bigint(); //default constructor

bool operator==(const bigint& num1); 

bigint( int n);

bigint(char new_digits[]);


private:
    int digit[MAX];
    int digitb[MAX];

};

here is the implementation file:

#include "bigint.h"
#include<cassert>
#include<iostream>


//default constructor
bigint::bigint()
{
     for (int i = 0; i < MAX; i++) 
     {
    digit[i] = 0;
     }

     }


     bigint::bigint( int n )
     {
    int i = 0;



      while(n > 0)
    {
       digit[i] = n % 10;
       n = n /10;
       ++i;
break;
     }


  for(i; i< MAX; ++i)
      digit[i] = 0;


     }

 bool bigint::operator==(const  bigint& num1)
     {

       for(int i = 0; i < MAX; i++)
          {
        if (num1.digit == num1.digit)
              return true;
          }
        return false;

      }


   bigint::bigint(char new_digit[])
      {
     int i = 0;

         //Reads the characters of numbers until it is ended by the null symbol

            while(new_digit[i] != '\0')
             ++i;

             --i;

       //Converts the characters into int values and puts them in the digit array
         while( i >= 0)
    {
            digit[i] = new_digit[i] - '0';
            --i;
    }


}


}



int main()
  {

     #include<iostream>

using namespace std;
using PROJECT_1::bigint;

bigint a(0);

assert(a == 0);
  }

BTW, I'm not trying to get the answers for my homework that I just started an hour ago. I've been working on this all day and I finally gave in and asked for help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

暖伴 2025-01-05 17:44:48

operator== 内循环的内容不起作用。您所做的是将 num1digit 数组(技术上是一个指针)与 num1< 的 digit 数组指针进行比较/代码>。这永远是真的。您应该将 this->digit 中的每个索引与 num1.digit 中的相应索引进行比较。像这样的:

bool bigint::operator==(const  bigint& num1)
{
    for(int i = 0; i < MAX; i++)
    {
        if (digit[i] != num1.digit[i])
            return false;
    }
    return true;
}

如您所见,我还将比较从等于更改为不等于。这是因为,如果两个 bigint 对象中只有第一个数字相同,那么使用 equal 将使函数在仅检查第一个数字后返回 true

The contents of the loop inside operator== is not working. What you are doing is comparing the digit array (which technically is a pointer) of num1 with the digit array pointer of num1. This will always be true. You should be comparing each index in this->digit to the corresponding index in num1.digit. something like this:

bool bigint::operator==(const  bigint& num1)
{
    for(int i = 0; i < MAX; i++)
    {
        if (digit[i] != num1.digit[i])
            return false;
    }
    return true;
}

As you can see, I also changed the comparison from equal to not-equal. This is because otherwise if only the first digit is the same in both bigint objects then using equal would have the function return true after only checking the first digit.

情绪操控生活 2025-01-05 17:44:48

您的代码存在许多问题。最直接的一个
已经指出:==运算符两边的表达式
是相同的,所以函数自然会返回 true。最
在 C++ 中编写此函数的惯用方法是:

return std::equals( 
    std::begin( digit ), std::end( digit ), std::begin( num1.digit ) );

在专业代码中,我会认为其他任何编程都是糟糕的。
在学生作业中,情况不太清楚,因为目标之一可能是
去学习如何自己写这样的东西,你可能不被允许
在这种情况下使用标准算法。我仍然会选择同样的方式
然而,基本方法是使用“迭代器”,而不是
索引:

int const* current = std::begin( digit );
int const* other   = std::begin( num1.digit );
int const* end     = std::end( digit );
while ( current != end && *current == *other ) {
    ++ current;
    ++ other;
}
return current == end;

至于代码的其余部分:

  • operator== 绝对应该是const;否则,即使像 myBigInt == 0 这样简单的东西也无法工作。

  • 事实上,operator== 可能应该是非成员。我喜欢有
    成员函数 isEqual,并且具有 operator== (并且
    operator!=) 调用它,但使其成为 friend 是完全有效的
    选项也是如此。

  • 不确定 digitb 应该做什么。

  • 您使用 int 的构造函数与使用的构造函数不兼容
    char[]。您需要决定您的内部代表是否是
    大端或小端。小尾数可能更容易
    算术运算,但这意味着你必须处理
    BigInt( char[] ) 中的数字按相反顺序排列。事实上,你开始
    就像您要以相反的顺序处理字符一样,但是
    你最终会向后遍历两个数组,永远不会初始化结束
    digit,并且不改变顺序。 (您还需要检查
    每个 char 实际上都是一个数字 - 使用标准 isdigit
    函数。)

一般来说,只要标准函数执行以下操作,您就应该使用它们
工作(并且您的任务允许)。在 BigInt::BigInt( char[] ) 中,对于
例如, new_digit + strlen( new_digit ) 会给你一个
“迭代器”到'\0'。 (使用迭代器去
向后比向前有点棘手,因为你不是
允许将其递减到数组前面之外。诸如此类:

const const* source = new_digits + strlen( new_digits );
while ( source != new_digits ) {
    -- source;
    //  ...
}

但是效果很好。

There are a number of problems with your code. The most immediate one
has been pointed out: the expression on both sides of the == operator
is identical, so naturally the function returns true. The most
idiomatic way of writing this function in C++ would be:

return std::equals( 
    std::begin( digit ), std::end( digit ), std::begin( num1.digit ) );

In professional code, I would consider anything else poor programming.
In a sudent assignment, it's less clear, since one of the goals may be
to learn how to write such things yourself, and you may not be allowed
to use the standard algorithms in such cases. I'd still go for the same
basic approach, however, using “iterators”, rather than
indexes:

int const* current = std::begin( digit );
int const* other   = std::begin( num1.digit );
int const* end     = std::end( digit );
while ( current != end && *current == *other ) {
    ++ current;
    ++ other;
}
return current == end;

As for the rest of the code:

  • operator== should definitely be const; otherwise, even something as simple as myBigInt == 0 won't work.

  • In fact, operator== should probably be a non-member. I like having
    a member function isEqual, and having operator== (and
    operator!=) call it, but making it a friend is a perfectly valid
    option as well.

  • Not sure what digitb is supposed to do.

  • You're constructor using int isn't compatible with the one using
    char[]. You need to decide whether your internal representation is
    big-endian or little-endian. Little-endian is probably easier for
    the arithmetic operations, but it means you'll have to process the
    digits in the reverse order in BigInt( char[] ). In fact, you start
    out as if you're going to process the characters in reverse order, but
    you end up going backwards over both arrays, never initializing the end
    of digit, and not changing the order. (You also need to check that
    each char really is a digit—using the standard isdigit
    function.)

In general, you should be using standard functions whenever they do the
job (and your assignment allows it). In BigInt::BigInt( char[] ), for
example, new_digit + strlen( new_digit ) will give you an
“iterator” to the '\0'. (Using an iterator to go
backwards is a bit trickier than going forwards, because you're not
allowed to decrement it beyond the front of the array. Something like:

const const* source = new_digits + strlen( new_digits );
while ( source != new_digits ) {
    -- source;
    //  ...
}

works well, however.

撕心裂肺的伤痛 2025-01-05 17:44:48

好吧,我认为你的比较实现不正确(我可能是错的,因为你没有指定比较的条件是什么,所以这是我的假设)因为:

你正在比较同一个传递的 bigint 中的两个数字,请看这个:

bool bigint::operator==(const  bigint& num1)
{
    for(int i = 0; i < MAX; i++)
    {
        if (num1.digit == num1.digit) // it'll be always true
        return true;
    }
    return false;
}

因此,由于这是作业,我不会给出精确的解决方案,但对于方法,请逐位比较并参见this 关于运算符重载,它应该有帮助。阅读、尝试和学习。

对于第二个问题,每行需要打印 80 个数字,因此运行一个循环,从头到尾打印所有字符,当循环计数器达到 80(或者从 0 开始为 79)时,输出换行符。这是一种解决方案。

下次把要求说得更清楚。

Well I think your implementation of comparing is not correct (i maybe wrong because you haven't specified what is the condition of comparison, so it is my assumption) because:

You are comparing the two numbers in the same passed bigint, see this:

bool bigint::operator==(const  bigint& num1)
{
    for(int i = 0; i < MAX; i++)
    {
        if (num1.digit == num1.digit) // it'll be always true
        return true;
    }
    return false;
}

So since this is homework, i am not giving exact solution, but for method, compare digit by digit and see this on operator overloading, it should help. Read, try and learn.

For the second question, you need to print 80 digits per line, so run a loop, from start to finish for all characters, and when loop counter reaches 80 (or 79 is you are starting from 0), output a newline character. This is one solution.

And mention requirements clearer next time.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文