Kotlin程式:求矩形的周長


在本文中,我們將瞭解如何求矩形的周長。矩形的周長使用以下公式計算:

2*(length + width)

下面是一個演示:

假設我們的輸入是:

The length of the sides of a rectangle are: 5, 8, 5, 8

期望的輸出是:

Perimeter : 26

演算法

  • 步驟1 - 開始

  • 步驟2 - 宣告三個整型變數:length(長)、width(寬)和myResult(結果)。

  • 步驟3 - 定義變數值。

  • 步驟4 - 使用公式 2 * (length + width) 計算周長,並將結果儲存在myResult中。

  • 步驟5 - 顯示周長值。

  • 步驟6 - 結束

示例1

在這個例子中,我們將使用上面給出的公式來求矩形的周長。首先,宣告並設定變數length和width:

val length = 5
val width = 8

然後,使用length和width求矩形的周長:

val myResult = 2 * (length + width)

讓我們來看一個計算矩形周長的例子:

fun main() { val length = 5 val width = 8 println("The sides of the rectangle are defined as $length, $width, $length, $width") val myResult = 2 * (length + width) println("Perimeter of rectangle is: $myResult") }

輸出

The sides of the rectangle are defined as 5, 8, 5, 8
Perimeter of rectangle is: 26

示例2

在這個例子中,我們將求矩形的周長。

fun main() { val length = 5 val width = 8 println("The sides of the rectangle are defined as $length, $width, $length, $width") getPerimeter(length, width) } fun getPerimeter(length: Int, width: Int) { val myResult = 2 * (length + width) println("Perimeter of rectangle is: $myResult") }

輸出

The sides of the rectangle are defined as 5, 8, 5, 8
Perimeter of rectangle is: 26

更新於:2022年10月13日

425 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告