在 PL/SQL 中統計數字中奇數和偶數的個數
給定一個正整數,任務是使用 PL/SQL 計算數字中奇數和偶數的個數。
PL/SQL 是 SQL 與程式語言的過程特性相結合的產物。它由 Oracle 公司在 90 年代初期開發,以增強 SQL 的功能。
PL/SQL 是嵌入在 Oracle 資料庫中的三種主要程式語言之一,另外兩種是 SQL 本身和 Java。
輸入
int number = 23146579
輸出
count of odd digits in a number are : 5 count of even digits in a number are : 3
說明 − 在給定的數字中,我們有 2、4、6 作為偶數,因此數字中偶數的個數為 3;我們有 3、1、5、7 和 9 作為奇數,因此數字中奇數的個數為 5。
輸入
int number = 4567228
輸出
count of odd digits in a number are : 2 count of even digits in a number are : 5
說明 − 在給定的數字中,我們有 5 和 7 作為奇數,因此數字中奇數的個數為 2;我們有 4、6、2、2 和 8 作為偶數,因此數字中偶數的個數為 5。
下面程式中使用的演算法如下
將數字輸入到 PL/SQL 中 NUMBER 資料型別的整型變數中。
使用 VARCHAR(50) 型別定義長度,它描述了可以儲存的最大長度。
取兩個變數作為奇數計數和偶數計數,並將其初始值設定為 0。
從 1 到長度開始迴圈,並將數字傳遞給它。
在迴圈內部,將長度設定為 substr(number, i, 1)。
現在,檢查 length 對 2 取模是否不等於 0,如果是則增加數字中奇數的計數。
否則,增加數字中偶數的計數。
列印結果。
示例
DECLARE digits NUMBER := 23146579; length VARCHAR2(50); count_odd NUMBER(10) := 0; count_even NUMBER(10) := 0; BEGIN FOR i IN 1..Length(digits) LOOP length := Substr(digits, i, 1); IF mod(length, 2) != 0 THEN count_odd := count_odd + 1; ELSE count_even := count_even + 1; END IF; END LOOP; dbms_output.Put_line('count of odd digits in a number are : ' || count_odd); dbms_output.Put_line('count of even digits in a number are : ' || count_even); END;
輸出
如果我們執行上面的程式碼,它將生成以下輸出:
count of odd digits in a number are : 5 count of even digits in a number are : 3
廣告