科特林程式以新增兩個複數
在本文中,我們將瞭解如何在科特林中新增兩個複數。它們具有與之關聯的“I”,即虛部。
下面是相同內容的演示 −
假設我們的輸入是
15 +i24 and 3 +i7
理想的輸出可能是
18 +i31
演算法
第 1 步 − 開始
第 2 步 − 宣告三個複數:inputValue1、inputValue2 和 myResult
第 3 步 − 硬編碼複數的值
第 4 步 − 定義一個函式 addComplexNumber,在其中分別新增實數和虛數並返回結果。
第 5 步 − 將結果儲存在 myResult 變數中。
第 6 步 − 顯示結果
第 7 步 − 停止
例項 1
在本示例中,我們在科特林中新增兩個複數
class Complex(internal var real: Double, internal var imaginary: Double) fun main() { val inputValue1 = Complex(15.0, 24.0) val inputValue2 = Complex(3.0, 7.0) System.out.printf("The input values are (%.1f, i%.1f) and (%.1f, i%.1f)
" ,inputValue1.real, inputValue1.imaginary , inputValue2.real, inputValue2.imaginary) val myResult = Complex(0.0, 0.0) myResult.real = inputValue1.real + inputValue2.real myResult.imaginary = inputValue1.imaginary + inputValue2.imaginary System.out.printf("The sum of the complex number is %.1f + i%.1f", myResult.real, myResult.imaginary) }
輸出
The input values are (15.0, i24.0) and (3.0, i7.0) The sum of the complex number is 18.0 + i31.0
例項 2
在本示例中,我們將使用自定義函式在科特林中新增兩個複數
class Complex(internal var real: Double, internal var imaginary: Double) fun main() { val input1 = Complex(15.0, 24.0) val input2 = Complex(3.0, 7.0) val myResult: Complex System.out.printf("The input values are (%.1f, i%.1f) and (%.1f, i%.1f)
" ,input1.real, input1.imaginary , input2.real, input2.imaginary) myResult = addComplexNumbers(input1, input2) System.out.printf("The sum of the complex number is %.1f + i%.1f", myResult.real, myResult.imaginary) } fun addComplexNumbers(input1: Complex, input2: Complex): Complex { val myResult = Complex(0.0, 0.0) myResult.real = input1.real + input2.real myResult.imaginary = input1.imaginary + input2.imaginary return myResult }
輸出
The input values are (15.0, i24.0) and (3.0, i7.0) The sum of the complex number is 18.0 + i31.0
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP