首页 > 解决方案 > 做while循环错误信息(身份错误)

问题描述

我正在尝试使用此代码提示用户提供一个数字并设置答案应介于 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);
^

标签: cfunctiondo-whilecs50

解决方案


您的问题不在于循环的语法错误。问题是你没有把它放在任何函数中,所以编译器在那个上下文中没想到循环。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函数内部的,而不是一个人站在那里。


推荐阅读