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

Why are the complex numbers printed here incorrect?

本文关键字:不正确 这里 打印 为什么      更新时间:2023-10-16

我正在尝试完成使用复数运算的 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. 使它们只采用一个参数,其中两个复数操作为接收对象和参数。然后,您可以选择是让这些函数修改接收器还是返回新值。

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

希望这有帮助!