首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Bigint *算子

Bigint *算子
EN

Stack Overflow用户
提问于 2013-07-19 20:25:13
回答 1查看 637关注 0票数 0

我正在做一个bigint项目,我很困惑为什么我的乘法运算符在测试用例上不能正常工作。

我将.h文件排除在外,因为它可能没有必要。

bigint.cpp:

代码语言:javascript
复制
// Definition of multiplication operator
BigInt BigInt::operator*(BigInt addend2)
{
 BigInt product;
   short int first,                  // a block of 1st addend (this object)
             second,                 // a block of 2nd addend (addend2)
             result,                 // a block in their sum
             carry = 0;              // the carry in adding two blocks

   list<short int>::reverse_iterator // to iterate right to left
      it1 = myList.rbegin(),         //   through 1st list, and
      it2 = addend2.myList.rbegin(); //   through 2nd list

   while (it1 != myList.rend() || it2 != addend2.myList.rend())
   {
      if (it1 != myList.rend())
      {
         first = *it1;
         it1++ ;
      }
      else
         first = 0;
      if (it2 != addend2.myList.rend())
      {
         second = *it2;
         it2++ ;
      }
      else
         second = 0;

      short int temp = first * second;
      result = temp % 1000;
      carry = temp / 1000;
      product.myList.push_front(result);
   }

   if (carry > 0)
      product.myList.push_front(carry);

   return product;
}

Main.cpp (测试用例):

代码语言:javascript
复制
int main()
{
    char response;
       do
       {
      cout << "\nMultiplication part:" << endl;
      cout << "The multiplication of\n\t"
           << number1 << " * " << number2
           << "\nis\n\t" << number1 * number2 << endl;

      cout << "\nAdd more integers (Y or N)? ";
      cin >> response;
}

当我运行代码时,乘法是错误的。

下面是一个样本: 123 * 423的乘法是-507,这显然是不正确的。

我很确定我搞砸了乘法的定义,但是谁能说出我在哪里搞砸了?

编辑:只是让大家知道,我的代码确实编译,但产品有时是错误的。我也把我所有的短int改为长int。

例如:

978 * 878 =858 684正确

但是当我使用更大的数字时,问题就出现了。

示例:

432,454 * 765,534 = 330,722,436,不正确。正确答案是3.32 * 10^11

EN

回答 1

Stack Overflow用户

发布于 2013-07-19 20:36:09

不要对中间值使用short int:1000 * 1000可能会导致短值溢出。使用int,理想的地方是static_assert(1000 * 1000 <= std::numeric_limits<int>::max()), "oops - int is too small!");

123 * 423 = 52029。在带有16位短路的两台补码机上,无符号短(52029)= -13507。-13507 % 1000 = -507。我不知道行李怎么了。不过。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17754879

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档