2

上下文:.Net,C#

我想打印一个由两个双打组成的复数。符号需要显示在虚部。我想为每个部分使用默认的双重格式以尽量减少字符数。

我尝试使用 String.Format("{0:+G;-G}{1:+G;-G}j", real, imaginary) 但这最终打印:“+G-Gj”。不完全是我想要的。

有没有办法使用 G 说明符来做到这一点,或者我需要做一个自定义格式,这会牺牲自动切换指数,​​例如 {1:+#.######e###;-#.# #####e###}j"

4

2 回答 2

3

这是不寻常的,但您可以轻松地覆盖您的 Complex 类的 ToString 方法。例如:

  class Complex {
    private double mReal, mImaginary;
    public Complex(double real, double imag) { mReal = real; mImaginary = imag; }
    private string WithSign(double value) {
      return value >= 0 ? "+" + value.ToString("N") : value.ToString("N");
    }
    public override string ToString() {
      return WithSign(mReal) + "i" + WithSign(mImaginary);
    }
  }

示例用法:

  static void Main(string[] args) {
    var c = new Complex(1, -1);
    Console.WriteLine(c.ToString());
    Console.ReadLine();
  }

输出:

  +1.00i-1.00

根据需要进行调整。

于 2010-04-06T22:39:20.310 回答
0

这恐怕是遥遥无期了……

怎么样:

String.Format("+{0:g}-{0:g}{1:g}-{1:g}j", real, imaginary)
于 2010-04-06T22:26:42.773 回答