C语言作为一门经典的编程语言,拥有广泛的应用场景。通过趣味编程例题,不仅可以提升编程技能,还能在挑战中找到乐趣。以下是一些精选的C语言趣味编程例题,旨在激发你的编程智慧。

一、猜数字游戏

题目描述: 编写一个猜数字的小游戏,让用户从0到100之间随机生成一个数字,用户可以多次猜测,每次猜测后程序会提示用户猜大还是猜小,直到猜中为止。

实现方法:

  1. 生成一个随机数作为目标数。
  2. 读取用户的猜测并比较。
  3. 根据比较结果提示用户猜大还是猜小。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
    int target, guess, attempts = 0;

    // 生成随机数
    srand(time(NULL));
    target = rand() % 101;

    printf("Guess the number between 0 and 100:\n");

    while (1) {
        scanf("%d", &guess);
        attempts++;

        if (guess == target) {
            printf("Congratulations! You've guessed the number in %d attempts.\n", attempts);
            break;
        } else if (guess < target) {
            printf("Try again, the number is bigger.\n");
        } else {
            printf("Try again, the number is smaller.\n");
        }
    }

    return 0;
}

二、反转字符串

题目描述: 编写一个函数,接受两个参数,分别为字符串和字符串长度,返回一个新的字符串,该字符串是原字符串的反转。

实现方法:

  1. 创建一个与原字符串等长的字符数组。
  2. 从原字符串的尾部开始,将字符依次复制到新数组中。
  3. 返回新数组。
#include <stdio.h>
#include <string.h>

void reverseString(char *str, int len) {
    int start = 0;
    int end = len - 1;
    char temp;

    while (start < end) {
        temp = str[start];
        str[start] = str[end];
        str[end] = temp;
        start++;
        end--;
    }
}

int main() {
    char str[] = "Hello, World!";
    int len = strlen(str);

    printf("Original string: %s\n", str);
    reverseString(str, len);
    printf("Reversed string: %s\n", str);

    return 0;
}

三、计算阶乘

题目描述: 编写一个函数,接受一个整数n作为参数,返回n的阶乘。

实现方法:

  1. 初始化结果为1。
  2. 从1循环到n,每次将结果乘以循环变量。
  3. 返回结果。
#include <stdio.h>

long long factorial(int n) {
    long long result = 1;
    for (int i = 1; i <= n; i++) {
        result *= i;
    }
    return result;
}

int main() {
    int n;
    printf("Enter a number to calculate its factorial: ");
    scanf("%d", &n);

    printf("Factorial of %d is %lld\n", n, factorial(n));

    return 0;
}

通过以上趣味编程例题,你可以在实践中提升C语言编程技能,并在解决问题的过程中享受编程带来的乐趣。