作者:tANGjIAqIAN

题目1

for循环

#include <stdio.h>
int main() {
    int n, i;
    long long nnn = 1; // 使用long long以存储较大的阶乘结果
    scanf("%d", &n);
    for (i = 1; i <= n; i++) {
        nnn *= i;
    }

    printf("%d! = %lld\n", n, nnn);
    return 0;
}

while循环

#include <stdio.h>

int main() {
    int n, i = 1;
    long long nnn = 1;
    scanf("%d", &n);
    while (i <= n) {
        nnn *= i;
        i++;
    }

    printf("%d! = %lld\n", n, nnn);
    return 0;
}

image

do-while循环

#include <stdio.h>

int main() {
    int n, i = 1;
    long long nnn = 1;
    scanf("%d", &n);
    do {
        nnn *= i;
        i++;
    } while (i <= n);

    printf("%d! = %lld\n", n, nnn);
    return 0;
}

image

题目2

#include <stdio.h>

// 函数用于计算绝对值
double absolute(double value) {
    if (value < 0) {
        return -value;
    } else {
        return value;
    }
}

int main() {
    double pi = 0.0;
    double term;
    int i = 0;
    const double epsilon = 1e-7;

    do {
        term = (i % 2 == 0 ? 1.0 : -1.0) / (2 * i + 1);
        pi += term;
        i++;
    } while (absolute(term) >= epsilon);

    pi *= 4.0; // 乘以4得到π的近似值

    printf("%f\n", pi);
    return 0;
}

image

题目3

#include <stdio.h>

int main() {
    int n1 = 0, n2 = 1, nextTerm, count = 0;

    printf("斐波那契数列的前20个数字是:\n");

    while (count < 20) {
        // 打印当前项
        printf("%d ", n1);

        // 计算下一项
        nextTerm = n1 + n2;
        n1 = n2; // 更新n1为前一项
        n2 = nextTerm; // 更新n2为当前项

        count++; // 增加计数
    }
    return 0;
}

image

题目4

#include <stdio.h>

int main() {
    int num, reversed = 0, remainder, original;

    // 提示用户输入一个整数
    printf("请输入一个整数:");
    scanf("%d", &num);

    // 保存原始数字
    original = num;

    // 反转数字
    while (num != 0) {
        remainder = num % 10; // 获取最后一位数字
        reversed = reversed * 10 + remainder; // 将数字添加到反转数字中
        num /= 10; // 移除最后一位数字
    }

    // 输出反转后的数字
    printf("反转后的数字是:%d\n", reversed);

    return 0;
}

image

posted on 2024-11-10 11:52  GaPb  阅读(10)  评论(0编辑  收藏  举报