Swift程式計算商和餘數


本教程將討論如何編寫一個Swift程式來計算商和餘數。

在除法過程中,一個數被另一個數除以得到一個結果數。或者我們可以說,除法是一個將較大數的組分成較小數的組的過程,這樣每個組都包含相同數量的元素。除法的四個主要術語是:

被除數 - 被除數是被除的數。

除數 - 除數是用來除的數。

- 商是除法得到的結果。

餘數 - 餘數是剩餘的數。

以下是相同的演示:

輸入

假設我們給定的輸入是:

Dividend 40
Divisor 10

輸出

期望的輸出將是

Quotient 4
Remainder 0


我們可以使用以下兩種方法找到商和餘數:

方法1 - 使用公式

為了找到商,我們必須使用 / 運算子將被除數除以除數,而為了找到餘數,我們必須使用 % 運算子。這裡被除數和除數都可以是任何資料型別,除了字串,結果將相應計算。

公式

以下是商的公式

Quotient = Dividend/Divisor

以下是餘數的公式

Remainder = Dividend % Divisor

演算法

以下是演算法:

  • 步驟1 - 宣告兩個變數,並賦予使用者定義/預定義的值。這裡這些變數用於儲存被除數和除數。

  • 步驟2 - 使用以下公式找到商,並將結果儲存到 myQuotient 變數中。

var myQuotient = myDividend / myDivisor
  • 步驟3 - 使用以下公式查詢餘數,並將結果儲存到 myRemainder 變數中。

var myRemainder = myDividend % myDivisor
  • 步驟4 - 列印輸出。

示例

下面的程式演示瞭如何使用公式計算商和餘數。

import Foundation import Glibc var myDividend = 105 var myDivisor = 2 // Finding quotient var myQuotient = myDividend/myDivisor // Finding remainder var myRemainder = myDividend%myDivisor print("The quotient of \(myDividend) and \(myDivisor) is", myQuotient) print("The remainder of \(myDividend) and \(myDivisor) is", myRemainder)

輸出

The quotient of 105 and 2 is 52
The remainder of 105 and 2 is 1

在上面的程式碼中,我們有被除數 = 105 和除數 = 2。所以我們首先使用以下公式找到它們的商

公式

myQuotient = myDividend/myDivisor = 105/2 = 52
Then we find the remainder using the following formula
myRemainder = myDividend%myDivisor = 105%2 = 1
And display the value of quotient and remainder

方法2 - 使用預定義函式

Swift 還提供了一個內建函式來查詢商和餘數。quotientAndRemainder(dividingBy:) 函式用於透過將值除以指定值來查詢商和餘數。它總是返回一個元組作為結果,其中結果元組的第一個元素是商,第二個元素是餘數。

語法

以下是內建函式的語法

DividendVariable. quotientAndRemainder(dividingBy: divisorValue)

演算法

以下是演算法:

  • 步驟1 - 宣告一個名為 myDividend 的變數,並從使用者/預定義讀取值。這裡這個變數用於儲存被除數的值。

  • 步驟2 - 宣告一個名為 myDivisor 的變數,並從使用者/預定義讀取值。這裡這個變數用於儲存除數的值。

  • 步驟3 - 使用以下函式查詢商和餘數,並將結果儲存到一個元組中。

myDividend.quotientAndRemainder(dividingBy:myDivisor)
  • 步驟4 - 列印輸出。

示例

下面的程式演示瞭如何使用函式計算商和餘數。

import Foundation import Glibc print("Please enter the value of Dividend") var myDividend = Int(readLine()!)! print("Please enter the value of Divisor") var myDivisor = Int(readLine()!)! // Finding the quotient and remainder let(myQuotient, myRemainder) = myDividend.quotientAndRemainder(dividingBy:myDivisor) print("The quotient of \(myDividend) and \(myDivisor) is", myQuotient) print("The remainder of \(myDividend) and \(myDivisor) is", myRemainder)

標準輸入

Please enter the value of Dividend
117
Please enter the value of Divisor
3

輸出

The quotient of 117 and 3 is 39
The remainder of 117 and 3 is 0

在上面的程式碼中,我們使用 readLine() 函式從使用者讀取被除數和除數的值,然後使用 Int() 函式將輸入值轉換為整數型別。現在我們使用 quotientAndRemainder() 函式找到給定值的商和餘數,並將結果儲存到一個元組中。顯示 117 除以 3 的商是 39,餘數是 0。

更新於:2022年8月18日

589 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

開始
廣告