为什么这里打印的复数不正确?

Why are the complex numbers printed here incorrect?

我正在尝试完成一个用复数运算的c++赋值代码。我在操作中使用的逻辑非常好,但我无法按照我的意愿输出结果。这一定是一个逻辑错误,但我就是不明白。

我试过构造函数、参数化等等,但我就是不明白。

#include<iostream>
using namespace std;
class complex
{
     int r, i;
public:
    int Read()
    {
        cout << "Enter Real part" << endl;
        cin >> r;
        cout << "Enter Imaginary part" << endl;
        cin >> i;
        return 0;
    }

    complex Add(complex A, complex B)
    {
        complex sum;
        sum.r = A.r + B.r;
        sum.i = A.i + B.i;
        return sum;
    }
    complex Subtract(complex A, complex B)
    {
        complex diff;
        diff.r = A.r - B.r;
        diff.i = A.i - B.i;
        return diff;
    }
    complex Multiply(complex A, complex B)
    {
        complex prod;
        prod.r = A.r*B.r + A.i*B.i*(-1);
        prod.i = A.r*B.i + B.r*A.i;
        return prod;
    }
    complex Divide(complex A, complex B)
    {
        complex c_B; //conjugate of complex number B
        c_B.r = B.r;
        c_B.i = -B.i;
        complex quotient;
        complex numerator;
        complex denominator;
        numerator.Multiply(A, c_B);
        denominator.Multiply(B, c_B);
        int commonDenom = denominator.r + denominator.i;
        quotient.r = numerator.r / commonDenom;
        quotient.i = numerator.i / commonDenom;
        return quotient;
    }

    int Display()
    {
        cout << r << "+" << i << "i" << endl;
        return 0;
    }

};

int main()
{
    complex a, b, c;
    cout << "Enter first complex number" << endl;
    a.Read();
    cout << "Enter second complex number" << endl;
    b.Read();
    c.Add(a, b);
    c.Display();
    c.Multiply(a, b);
    c.Display();



    system("pause");
    return 0;
}





the expected output on input of 1+2i and 2+3i should be
3+5i
8+i

but output is
-858993460+-858993460i
-858993460+-858993460i

看看这段代码:

c.Add(a, b);
c.Display(); // <- Here

这里需要考虑一下:您在这里显示的是哪个复数?

看看你的 Add 函数。请注意,调用 c.Add(a, b) 实际上并未将 c 设置为等于 ab 的总和。相反,它实际上忽略了 c(查看代码 - 请注意,您从未读取或写入接收方对象的任何字段),然后生成一个等于 a + b 的新复数。因此,当您调用 c.Display() 时,您并没有打印总和。相反,您正在获取从未初始化其数据成员的 c,并打印出其值。

您可以使用多种不同的策略来解决此问题。从根本上说,我会回顾一下您是如何定义 Add 和其他计算复数的成员函数的。如果那些成员函数不使用接收者对象,那么可以考虑

  1. 使它们成为 static 或自由函数,以便它们仅对两个参数进行操作,而不是两个参数加上一个隐式 this 参数,或

  2. 让他们只取一个参数,运算的两个复数作为接收对象和参数。然后您可以选择是让这些函数修改接收器还是 return 新值。

一旦您决定了要如何解决上述问题,请返回并查看您编写的用于添加和打印值的代码。您可能需要引入更多变量来显式捕获您执行的操作的总和、差等。

希望对您有所帮助!