【问题标题】:How to compare product of two variables in c++ without directly multiplying them(due to overflow)?如何在不直接相乘的情况下比较 C++ 中两个变量的乘积(由于溢出)?
【发布时间】:2021-01-13 07:57:15
【问题描述】:

如何计算 a*b > c*d 并存储一个值以供以后与任何其他两对比较。在 c++ 中乘法时乘积溢出。 long long a = 12345678912, b=45697845821, c=47896512354, d=741258963256;

【问题讨论】:

标签: c++ math overflow


【解决方案1】:

您可以转换为浮点数并比较 a/d 和 c/b。或者,您可以保留整数,如果 a/d == c/b 则比较 a%d 和 c%b。

【讨论】:

  • 非常好的建议(已经赞成)。您可能想详细说明阳性和阴性和 0 病例是否需要特别护理。
  • 是的,我假设所有数字都是严格的正数。实际上,比较 ​​a - d 和 c - b 也应该可以解决问题,并且适用于负数和零。根据数量级,比较 (a - d) + b 和 c 或 a 和 (c - b) + d 也可能是一种选择。
【解决方案2】:
#include<boost/multiprecision/integer.hpp>
void f()
{
    long long int a_ = 12345678912;
    long long int b_ = 45697845821;
    boost::multiprecision::int128_t a(a_);
    boost::multiprecision::int128_t b(b_);
    boost::multiprecision::int128_t ab(a * b); // store a value for later comparison with any other two pairs
    bool greater_than = ab > boost::multiprecision::int128_t(47896512354) * boost::multiprecision::int128_t(741258963256);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-24
    • 2018-03-06
    • 2014-03-13
    • 1970-01-01
    • 1970-01-01
    • 2015-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多