c-Do while loop错误消息(标识错误)



我试图使用此代码提示用户提供一个数字,并设置答案应在1和23之间(包括1和23(的条件。然而,当我尝试使用do-while循环时,它似乎抛出了一个我不熟悉的错误。

我的代码:

#include "stdio.h"
#include "cs50.h"
int n;
do
{
n = get_int("Enter a number: ");
}
while (n < 0 || n > 23);

错误:

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

问题不在于循环的语法错误。问题是你没有把它放在任何函数中,所以编译器不希望在那个上下文中出现循环。int n;在函数之外是有效的,这就是为什么在循环开始时会发生错误。试试这样的东西:

#include "stdio.h"
#include "cs50.h"
int main(int argc, char **argv)
{
// the program starts here; "main" is the function that is run when the program is started
int n;
do {
n = get_int("Enter a number: ");
}
while (n < 0 || n > 23);
// TODO: do something useful with the input
return 0; // The convention is that returning 0 means that everything went right
}

请注意,代码现在是如何位于main函数内部的,而不是仅仅站在那里。

最新更新