C# 中的复数

csharpprogrammingserver side programming

要在 C# 中使用和显示复数,您需要检查实数和虚数。

像 7+5i 这样的复数由两部分组成,实部 7 和虚部 5。这里,虚部是 i 的倍数。

要显示完整的数字,请使用 −

public struct Complex

要将两个复数相加,您需要将实部和虚部相加 −

public static Complex operator +(Complex one, Complex two) {
   return new Complex(one.real + two.real, one.imaginary + two.imaginary);
}

您可以尝试运行以下代码以在 C# 中处理复数。

示例

using System;
public struct Complex {
   public int real;
   public int imaginary;
   public Complex(int real, int imaginary) {
      this.real = real;
      this.imaginary = imaginary;
   }
   public static Complex operator +(Complex one, Complex two) {
      return new Complex(one.real + two.real, one.imaginary + two.imaginary);
   }
   public override string ToString() {
      return (String.Format("{0} + {1}i", real, imaginary));
   }
}
class Demo {
   static void Main() {
      Complex val1 = new Complex(7, 1);
      Complex val2 = new Complex(2, 6);
      // 将两者相加
      Complex res = val1 + val2;
      Console.WriteLine("First: {0}", val1);
      Console.WriteLine("Second: {0}", val2);
      // 显示结果
      Console.WriteLine("Result (Sum): {0}", res);
      Console.ReadLine();
   }
}

输出

First: 7 + 1i
Second: 2 + 6i
Result (Sum): 9 + 7i

相关文章