【问题标题】:Do While Loop in C (CS50)在 C 中执行 While 循环 (CS50)
【发布时间】:2020-08-27 21:46:31
【问题描述】:

我目前正在尝试学习 CS50 课程。我正在尝试为第一个问题集创建一个 do-while 循环,但我抛出了一个错误。帮助会很好,谢谢!

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

int main(void)
{

    do
    {
        printf("Enter a positive integer no greater than 23: \n");
        int n = get_int();
    }
    while ( int n < 0 || int n > 23);

}

$clang mario.c

mario.c:12:13: error: expected expression
    while ( int n < 0 || int n > 23);
            ^
mario.c:12:13: error: expected ')'
mario.c:12:11: note: to match this '('
    while ( int n < 0 || int n > 23);
          ^
2 errors generated.

【问题讨论】:

  • 只声明一次n,在do-while循环之外

标签: c do-while cs50


【解决方案1】:

在 do-while 循环之外只声明一次 n:

int n = -1;
do
{
    printf("Enter a positive integer no greater than 23: \n");
    n = get_int();
}
while (n < 0 || n > 23);

【讨论】:

  • 我可以在第一次声明时将 n 设置为我想要的任何数字吗?还是我什至必须将其设置为任何内容?
  • 是的,实际上,因为do() 循环会将其设置为输入
  • @R_C 是的,至少任何能够存储在int 中的东西。
【解决方案2】:

我们从不在内部定义变量 if 或 while 和 For 循环等表达式 这只有在 C++ 等其他语言中才有可能 |;

【讨论】:

  • 谢谢。我使用的是 Python,是 C 的新手。
【解决方案3】:

你的问题在于你有:

  • 在 while 循环中声明 n(这在 C89 中是不允许的,但在以后的版本中勉强允许)

  • 在 while 部分声明了两次 n

声明的想法是向编译器表明,存在的变量名不是垃圾,而是实际上是一个变量。编译器通常遵循固定规则,不会在 while/for 循环中查找变量名(这是出于优化目的)。此外,当您第二次声明 n 时,编译器现在感到困惑,因为您声明了一个名为 n 的变量已经存在。

PS:我相信你想说n lies within the bounds of 1 and 22 如果你想说这个,正确的表达将涉及AND (&amp;&amp;) 而不是OR (||) 即while ( int n &lt; 0 &amp;&amp; int n &gt; 23)

【讨论】:

    最近更新 更多