阿摩線上測驗 登入

申論題資訊

試卷:98年 - 98 關務特種考試_四等_資訊處理:程式語言概要#34304
科目:程式語言
年份:98年
排序:0

題組內容

一、請撰寫程式。 設整數陣列 INTDATA[M][N]已存值,請分別撰寫函數(Function)之副程式如下述, 並寫一主程式呼叫該函數,計算其值且列印出。

申論題內容

⑴函數 POSF 為找 INTDATA 中的正值之項數,將此值存入 NPOS 並列印出。(12 分)

詳解 (共 1 筆)

詳解 提供者:hchungw
def POSF(data):
    """
    This function takes a 2D list (matrix) and returns the number of positive integers in the matrix.
    """
    NPOS = 0
    for row in data:
        for item in row:
            if item > 0:
                NPOS += 1
    return NPOS
def main():
    # Example matrix INTDATA
    INTDATA = [
        [1, -2, 3],
        [-4, 5, -6],
        [7, -8, 9]
    ]
    # Call the POSF function to find the number of positive values
    NPOS = POSF(INTDATA)
    # Print the result
    print(f"The number of positive values in INTDATA is: {NPOS}")
if __name__ == "__main__":
    main()
程式說明
POSF 函數:
輸入參數為二維陣列(矩陣)。
使用雙層迴圈遍歷矩陣中的每個元素,並計算其中正數的個數。
返回正數的計數值。
主程式:
定義一個示例的二維陣列 INTDATA。
呼叫 POSF 函數並將結果存入變數 NPOS。
列印出 NPOS 的值,即矩陣中正數的個數。
這個程式會正確地計算並列印出 INTDATA 中的正值數量。你可以根據需要修改 INTDATA 的內容以測試不同的輸入。