显示复数

时间:2016-07-26 09:19:36

标签: c# tostring complex-numbers

我有一个复数的数字类,其输出覆盖了ToString。

复数的结构有五种情况,每种情况都需要稍微不同的输出格式:

a == 0, b == 0: "0"  
a == 0, b != 0: "bi"  
a != 0, b > 0: "a + bi"  
a != 0, b < 0: "a - |b|i"  
a != 0, b == 0: "a"  

我有这个并且它有效:

public override string ToString() {
            if (this.real == 0) {
                if (this.imaginary == 0) return "0";
                else return this.imaginary.ToString() + "i";
            }
            else {
                if (this.imaginary == 0) return this.real.ToString();
                else if(this.imaginary > 0) return this.real.ToString() + " + " + this.imaginary.ToString() + "i";
                else return this.real.ToString() + " - " + (this.imaginary * -1).ToString() + "i";
            }
        }

有更清洁的方法吗?也许条件较少,可能的情况较少。

2 个答案:

答案 0 :(得分:0)

这个怎么样?

public override string ToString()
{
    if (this.real != 0 && this.imaginary > 0) return this.real.ToString() + " + " + this.imaginary.ToString() + "i";
    if (this.real != 0 && this.imaginary < 0) return this.real.ToString() + " - " + (-1 * this.imaginary).ToString() + "i"; 
    if (this.real != 0 && this.imaginary == 0) return this.real.ToString();
    if (this.imaginary != 0) return this.imaginary.ToString() + "i";    
    return "0";     
}

答案 1 :(得分:0)

我采用了Andy Taw的逻辑,修复了最后一个案例,并添加了一些三元来涵盖b = +/- 1的情况,在这种情况下我甚至不想显示b。

public override string ToString() {
            if (this.real != 0 && this.imaginary > 0) return this.real.ToString() + " + " + ((this.imaginary == 1)?"":this.imaginary.ToString()) + "i";
            else if (this.real != 0 && this.imaginary < 0) return this.real.ToString() + " - " + ((this.imaginary == -1)?"":(-1 * this.imaginary).ToString()) + "i";
            else if (this.imaginary != 0) return ((this.imaginary == 1)?"":((this.imaginary == -1)?"-":this.imaginary.ToString())) + "i";
            else return this.real.ToString();
        }