C语言基础之函数和流程控制

 函数和流程控制也是每个编程语言的基本概念,函数是划分模块的最小单位,良好的函数规划能直接提升软件的质量,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);
}


猜你喜欢

转载自blog.51cto.com/2648256/2135790