我很难使用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;
}
答案 0 :(得分:2)
该函数的主要问题是将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
这是一个repl。
答案 1 :(得分:1)
两件事:
查看以下更改:
while (counter > 20) {
// Subtract 5 from the counter.
counter -= 5;
// Print the value of the counter on a line by itself.
printf("%d\n", counter);
}
答案 2 :(得分:1)
尽管其他答案已就如何解决您的方法提出了意见,但应注意,while
循环比for
循环更合适,因为它是为此目的而设计的。
for(int counter = 100; counter >= 20; counter -= 5) {
printf("%d\n", counter);
}
答案 3 :(得分:0)
似乎,您永远不会更改counter的值,而while内的条件似乎是错误的。 尝试:
#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);
// (c) 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.
counter = counter - 5;
printf(counter);
}
}
int main( void ) {
count_down();
return 0;
}
答案 4 :(得分:0)
您可以尝试以下方法:
#include <stdio.h>
void count_down(int counter) {
// Declare an integer variable that you will use to count. Initially
// the counter should equal the start value, 100.
printf("%d\n", 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.
// Subtract 5 from the counter.
counter = counter - 5;
printf("%d\n", counter);
}
}
int main( void ) {
count_down(100);
return 0;
}