【发布时间】:2017-08-03 23:09:36
【问题描述】:
void ComplexNum::printComplexNum()
{
if (imaginary = 1)
{
return ""; //cannot return "" I've also tried imaginary == ""; to no avail
}
cout << "(" << noshowpos << real << showpos << imaginary << "i)" << endl;
}
我有一个复数程序,当我想显示复数时,它会错误地显示它们,因为 (4-1i) 应该显示为 (4-i)。虽然 (4-1i) 在技术上是正确的,但它并没有像我希望的那样显示。我在 print 方法中创建了一个简单的 if 语句,但它不起作用,因为 imaginary 变量不是字符串。 *如何使我的变量 imaginary 等于 1 时返回 "" 或空白或什么都没有,以便它可以打印出我设置的适当的 "i)"。
样本输出:
First Complex Number:
Enter real part of complex number: 2
Enter imaginary part of complex number: -3
Form '(a+bi)': (2-3i)
Second Complex Number:
Enter real part of complex number: 4
Enter imaginary part of complex number: -4
Form '(a+bi)': (4-4i)
The addition of the two Complex Numbers is: (6-7i)
The difference of the two Complex Numbers is: (-2+1i)
The product of the two Complex Numbers is: (-4-20i)
First Complex Number Squared: (-5-12i)
Second Complex Number Squared: (0-32i)
注意区别是 (-2+1i)...我不喜欢那样。我不想要那个。另外,我不想要那个(0-32i)。所以基本上当它为 0 或为 1 时,我希望 print 函数能够反映这一点。所以差异看起来像 (-2+i) 而第二个复数平方看起来像 (32i)
现在进入我的代码:
class ComplexNum
{
public:
ComplexNum(float = 0.0, float = 0.0); //default constructor that uses default arg. in case no init. are in main
void getComplexNum(); //get real and imaginary numbers from keyboard
void sum(ComplexNum a, ComplexNum b); //method to add two ComplexNum numbers together
void diff(ComplexNum a, ComplexNum b); //method to find the difference of two complex numbers
void prod(ComplexNum a, ComplexNum b); //method to find the product of two complex numbers
void square(); //squares values of a and b when called in main
void printComplexNum(); //print sum, diff, prod, square
void formComplexNum(); //and "a+bi" form
private:
float real; //float data member for real number (to be entered in by user)
float imaginary; //float data member for imaginary number (to be entered in by user)
float realSquare; //squared real number data member for square method
float imaginarySquare; //squared imaginary number data member for square method
};
还有司机:
int main()
{
ComplexNum a, b, c, d, e, f, g;
cout << "First Complex Number:" << endl;
a.getComplexNum();
a.formComplexNum();
cout << endl;
cout << "Second Complex Number:" << endl;
b.getComplexNum();
b.formComplexNum();
cout << endl;
c.sum(a, b);
c.printComplexNum();
d.diff(a, b);
d.printComplexNum();
e.prod(a, b);
e.printComplexNum();
cout << "First Complex Number Squared: ";
a.square();
cout << "Second Complex Number Squared: ";
b.square();
cout << endl;
system("PAUSE");
return 0;
}
【问题讨论】:
-
您在 if 条件中将值 1 分配给变量。为什么不在 if 中使用另一个输出?
-
什么意思?
-
您似乎对
return的含义不熟悉。 -
我写了return和其他东西。是的,我知道 return 无效。因为 void 不返回任何东西。但还是。只是一个 if 语句在这里也不起作用。
-
我认为人们只是掩盖了我在那条线上写的评论。我特别提到我尝试过 "imaginary = ""; " 但这也没有用。只是想指出我已经尝试了一切。