为什么这里打印的复数不正确?
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
设置为等于a
和b
的总和。相反,它基本上忽略了c
(查看代码 - 请注意,您从不读取或写入接收器对象的任何字段),然后生成一个等于a + b
的新复数。因此,当您调用c.Display()
时,您不会打印总和。相反,您正在获取从未初始化其数据成员的c
,并打印出其值。
您可以使用几种不同的策略来解决此问题。从根本上说,我会回顾一下你是如何定义Add
和在复数上计算的其他成员函数的。如果这些成员函数不使用接收器对象,则考虑
使它们
static
或自由函数,以便它们只对两个参数进行操作,而不是两个参数加上一个隐式this
参数,或者使它们只采用一个参数,其中两个复数操作为接收对象和参数。然后,您可以选择是让这些函数修改接收器还是返回新值。
一旦您决定了如何解决上述问题,请返回并查看您编写的用于添加和打印值的代码。您可能需要引入更多变量来显式捕获已执行操作的总和、差异等。
希望这有帮助!
相关文章:
- 使用2个键的cpp-stl::优先级队列排序不正确
- 正弦级数方程计算不正确
- 我试图制作一个程序,要求用户输入问题和答案,但程序循环不正确
- 密码登录程序将永远循环并显示不正确的结果
- 在C++中返回不正确的楼层函数值
- 形状对象的旋转和缩放不正确C++
- C++ 读取文件读取文件不正确
- 关于类的 Python 文档 - 对C++的引用不正确
- 特征 LLT 模块给出不正确的结果?
- glibcxx STL 在实现 std::valarray::sum() 时是否不正确?
- 如果语句逻辑不正确
- 来自逆 vp 矩阵和相机位置的光线方向不正确
- 不正确的操作数类型 MSVC
- 数组填充了不正确的值
- 我是否不正确地集中了这些字符数组?
- 为什么除非我使用 cout,否则我的值不正确?
- 计算幂级数的数学结果不正确
- 为什么 sizeof 在 C++ 中给出不正确的字节数?
- atoi() 在应用于大型命令行参数时会产生不正确的值
- 为什么这里打印的复数不正确?