我在使用 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/