1. 程式人生 > >C語言基礎之函數和流程控制

C語言基礎之函數和流程控制

argv round ext 組成 htm pre 多個參數 nor ali

函數和流程控制也是每個編程語言的基本概念,函數是劃分模塊的最小單位,良好的函數規劃能直接提升軟件的質量,C語言的流程控制主要由以下幾個語句組成,條件分支語句、選擇語句、循環語句、goto語句、return語句等。

函數的定義

一個函數包含返回值、函數名和參數列表,如下定義了一個返回值為 int 函數名為show擁有一個int類型參數的函數

int show(int param) {
    printf("這是一個名為show的函數");
    return 0;
}

再來定義個沒有返回值,沒有參數列表的函數

void info(void) {
    printf("參數列表裏的void可以不要");
}

函數調用

#include <stdio.h>
int show(int param) {
    printf("show\n");
    return 0;
}

void info(void) {
    printf("info\n");
}

void multi_param(int a, int b, int c) {
    printf("多個參數用逗號分割\n");
}

int main(int argc, char *argv[]) {
    int result = show(10); ///調用show
    info(); ///調用info
    multi_param(1, 2, 3); ///調用

    return 0;
}

條件分支語句

void show_score(int score) {
    if (100 == score) {
        printf("滿分\n");
    }
}

void show_score(int score) {
    if (100 == score) {
        printf("滿分\n");
    } else {
        printf("不是滿分\n");
    }
}

void show_score(int score) {
    if (score >= 90) {
        printf("高分\n");
    } else if (score >= 60) {
        printf("及格\n");
    } else {
        printf("不及格\n");
    }
}

選擇語句

void show(int value) {
    switch (value) {
    case 1:
        printf("one\n");
        break;
    case 2:
        printf("two\n");
        break;
    case 3:
        printf("three\n");
        break;
    default:
        printf("以上都不滿足時,就到此處\n");
        break;
    }
}

循環語句

void plus() {
    int i, total = 0;
    /// 1 + 2 + 3 +...+ 100
    for (i = 1; i <= 100; i++) {
        total += i;
    }
    printf("result=%d\n", total);
}

void plus() {
    int i = 0, total = 0;
    /// 1 + 2 + 3 +...+ 100
    while (i <= 100) {
        total += i;
        i++;
    }
    printf("result=%d\n", total);
}
void plus() {
    int i = 0, total = 0;
    /// 1 + 2 + 3 +...+ 100
    do {
        total += i;
        i++;
    } while (i <= 100);
    printf("result=%d\n", total);
}


C語言基礎之函數和流程控制