以 5 为增量倒数

标签 c

我在使用 while 循环从起始数字 100 开始倒数时遇到困难。我需要以 5 为增量倒数,并显示每个结果,直到达到 20。

#include <stdio.h>

void count_down( void ) {

    // Declare an integer variable that you will use to count. Initially 
    //     the counter should equal the start value, 100.
    int counter = 100;
    printf(counter);
    // Begin a WHILE statement that will execute its loop body if the counter 
    // is greater than the end value, 20.

    while (counter < 20) {
        // Print the value of the counter on a line by itself.
        printf(counter);
        // Subtract 5 from the counter.
        int new_number = counter - 5;
        printf(new_number);
    }
}


int main( void ) {
    count_down();
    return 0;
}

最佳答案

您的函数的主要问题是您将 count 设置为 100,然后尝试进入一个永远不会激活的 while 循环(100 永远不会小于 20 )。如果您要进入此循环,则循环内的指令实际上不会更改循环条件变量,因此它会无限运行。

除此之外,我建议向您的函数添加参数,使其可重用于任何倒计时和任何步骤:

#include <stdio.h>

void count_down(int start, int end, int step) {
    while (start >= end) {
        printf("%d\n", start);
        start -= step;
    }
}

int main() {
    count_down(100, 20, 5);
    return 0;
}

输出:

100
95
90
85
80
75
70
65
60
55
50
45
40
35
30
25
20

关于以 5 为增量倒数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51701083/

相关文章:

c - 初始化器必须是常量

c - 查找以字符 X 开头的所有后缀

c - 希望文件中的每个单词都列在数组中

c - 传输端已连接错误: 106 with connect()

c - 使用 typedef 和结构时出错

c - 如何对 SMOB 类型执行条件语句?

c - 使用C语言结构体存储学生信息(姓名、学号、分数)并执行插入、删除、搜索的程序

c - 设置了一些参数的函数指针

c - 从其他库 (OS X/POSIX) 重新导出共享库符号

c - 如何在 C 程序的记事本中打开文本文件?