如何在以下示例代码中处理成员函数中的大数乘法运算

问题描述 投票:0回答:1

我正在按照教程和作业来计算盒子的体积。为此,编写了以下程序。

class Box
{
private:
    int length{ 0 }, breadth{ 0 }, height{ 0 };

public:
    Box() {};
    Box(int l, int b, int h) :length{ l }, breadth{ b }, height{ h } {};
    Box(Box& B) :length{ B.length }, breadth{ B.breadth }, height{ B.height } {};
    ~Box() {}

    int getLength()
    {
        return length;
    }
    int const getBreadth() { return breadth; }
    int const getHeight() { return height; }
    long long const CalculateVolume() { return static_cast<long long> (length * breadth * height);}

    bool operator<(Box& bx)
    {
        return (CalculateVolume() < bx.CalculateVolume());
    };

    friend std::ostream& operator<<(ostream& out, Box& bx)
    {
        out << bx.length << " " << bx.breadth << " " << bx.height;
        return out;
    }
};



int main()
{
    Box bx1(1039, 3749, 8473);
    std::cout << "Volume = " << bx1.CalculateVolume() << std::endl;


    // Define the values
    int value1 = 1039;
    int value2 = 3749;
    int value3 = 8473;

    // Multiply the values together
    long long result = static_cast<long long>(value1) * value2 * value3;

    // Output the result
    std::cout << "Result of multiplication: " << result << std::endl;



    return 0;
}

此处,体积计算不正确,并给出以下输出。

Volume = -1355615565

但是如果我将这三个值相乘,我就能得到正确的值。

Result of multiplication: 33004122803

似乎该值超出了数据类型的最大值,但我无法找出真正的原因。 Box 类的

CalculateVolume()
成员函数有什么问题。欢迎任何提示。

c++ oop
1个回答
0
投票

让我们首先观察到,在这两种情况下,三个变量都是

int
。接下来我们看一下两段代码:

  • return static_cast<long long> (length * breadth * height);
  • long long result = static_cast<long long>(value1) * value2 * value3;

在第一部分中,计算完全以变量的类型(

int
)执行,然后将结果转换为
long long
。这意味着在转换完成之前计算已完成并溢出。

在第二部分中,

value1
首先转换为
long long
,然后进行计算 - 但是当您将
int
long long
相乘时,则以更大的类型进行计算,因此不会发生溢出(因为结果确实符合
long long
)。

编辑:回复评论。

区别在于括号的位置:

cast(a) * b
cast(a * b)
。在您的评论中您仍然使用后一个版本:

long long const CalculateVolume() {
    long long result = static_cast<long long>(length * breadth * height);
    return result;
}

你也可以这样做:

long long const CalculateVolume() {
    long long temp = length;
    return temp * breadth * height;
}

重点是,当乘法中至少有一个操作数是

long long
时,那么整个计算都是以该类型完成的。

© www.soinside.com 2019 - 2024. All rights reserved.