C# 中的複數
要在 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);
// Add both of them
Complex res = val1 + val2;
Console.WriteLine("First: {0}", val1);
Console.WriteLine("Second: {0}", val2);
// display the result
Console.WriteLine("Result (Sum): {0}", res);
Console.ReadLine();
}
}輸出
First: 7 + 1i Second: 2 + 6i Result (Sum): 9 + 7i
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP