c - 如何编写正确的 do..while 循环?

标签 c loops cs50

由于某种原因,当我尝试编译该代码时,它会抛出错误。怎么了,你能告诉我吗? 我正在学习 CS50 类(class),这实际上是第一个作业。

程序必须提示用户输入,直到条件为假为止。

#include <stdio.h>
#include <cs50.h>

int n;

do
{
    n = get_int();
}
while ( n < 0 || n > 23 );

这是错误:

pyramid.c:6:1: error: expected identifier or '('
do
^
pyramid.c:10:1: error: expected identifier or '('
while ( n < 0 || n > 23 );

最佳答案

这是在 C 中使用 do {...} while(); 循环的通用示例。 cs50不是标准的C头文件,这是为参加cs50类(class)的学生自制的。

您应该检查get_int();定义在cs50.h头文件中。

代码:

#include <stdio.h>
int main()
{
    int number;

    // Do while loop is executed at least once
    do
    {
      printf("Enter a number from 0-23: ");
      scanf("%d", &number);

    }
    while(number < 0 || number > 23);

    printf("Number = %d\n",number);

    return 0;
}

关于c - 如何编写正确的 do..while 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52703987/

相关文章:

C 轮函数抛出错误 : "undefined reference to ` round'. ..”

Java - 对二维数组进行排序

c - 指向 C 中数组的第一个元素

c - 查询不同的值并遍历结果 MongoDB C API

c - 如何仅使用指针重写这个 strcpy() 函数?

Javascript while 循环使页面无法加载

python - 在Python 3.3中通过循环将键和值迭代到字典中

c - 通过 valgrind 从 cs50/pset5 拼写器运行 trie 字典时出现上下文错误

c - 在这个 CS50 问题集中,For 循环背后的数学原理是什么?

c - 即使使用 `noexecstack`,堆栈也是可执行的