Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

การนับตัวเลขคี่และคู่ในจำนวนเต็มด้วย PL/SQL

PL/SQL Program: นับหลักคี่และคู่

PL/SQL (Procedural Language/SQL) เป็นภาษาขยายของ Oracle Database ที่รวม SQL กับคุณสมบัติการเขียนโปรแกรมเชิงขั้นตอน

อัลกอริทึม

  1. รับค่าตัวเลขเข้ามา
  2. วนลูปผ่านแต่ละหลัก (ใช้ SUBSTR)
  3. ตรวจสอบ MOD(หลัก, 2) เพื่อแยกคี่/คู่
  4. นับจำนวนและแสดงผล

โค้ด PL/SQL

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

คำอธิบาย: ตัวเลข 23146579 มีหลักคี่: 3,1,5,7,9 (5 หลัก) หลักคู่: 2,4,6 (3 หลัก)

ตัวอย่างเพิ่มเติม: 4567228 → คี่: 5,7 (2 หลัก) คู่: 4,6,2,2,8 (5 หลัก)