c - 做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);
^
解决方案
您的问题不在于循环的语法错误。问题是你没有把它放在任何函数中,所以编译器在那个上下文中没想到循环。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
函数内部的,而不是一个人站在那里。
推荐阅读
- ios - Google Maps iOS:移动相机以显示集群内的所有标记
- javascript - 如何禁用 Firebase 电话身份验证 reCAPTCHA?(网络/反应)
- android - 为什么Camera2拍照这么慢?
- java - 从文件中读取并插入数组
- angular - 变量更改后更新视图
- json - 更改字典列表中的字典值
- php - Wordpress - 无法获取我页面的内容。收到关于 post-template.php 的错误
- javascript - 我想根据用户角色隐藏特定的导航栏
- python - 尝试在机器人框架中进行 For 循环时语法无效
- c - 如何修复错误:返回类型'struct {aka struct时的类型不兼容
}