【问题标题】:Trouble with inputs using a while loop使用 while 循环输入的问题
【发布时间】:2016-12-24 23:59:16
【问题描述】:
int towerh;
do{
    printf ("give me an integer between 1 and 23 and I will make a tower");
    int towerh = GetInt();
}while (towerh < 1 || towerh > 23);

只要towerh 不在 1 到 23 之间,我就会尝试使此代码块循环。我不断收到错误消息,提示需要初始化变量。

我确定这是一件小事,但我不知道如何在 C 中评估或更正它。

【问题讨论】:

  • 'int towerh; do{ printf ("给我一个 1 到 23 之间的整数,我会做一个塔");塔 = GetInt(); }while (towerh 23);'
  • 你应该添加cs50标签
  • 问题是你有两个变量叫做towerh,一个在循环体中声明,一个在循环体之外。循环条件测试循环外定义的变量,但GetInt()读取的值被赋值给循环内定义的变量。这超出了右括号的范围。您只需将int 放在循环内即可分配给循环外定义的变量。这就是 Daulton Sink 所展示的内容——但并未完全解释。

标签: c variables global local cs50


【解决方案1】:

只需将int towerh; 更改为int towerh = 0;。这称为初始化变量,通常 C 编译器会在您错过它时讨厌它。

另外,您在循环中一次又一次地创建towerh,我建议scanf 覆盖未提及的GetInt,因此您可以以:

int towerh = 0;
do {
    printf("Give me an integer between 1 and 23 and I will make a tower: ");
    scanf("%d", &towerh);
} while (towerh < 1 || towerh > 23);

【讨论】:

  • 在尝试后我得到一个错误声明阴影局部变量
  • 你尝试了完整的代码还是只是初始化?阴影变量意味着您在代码中再次以相同名称创建一个变量,就像您在循环中使用 int towerh 所做的那样
  • 只是初始化我现在已经修复了感谢您的帮助
【解决方案2】:

代码有 2 个towerh;。第一个永远不会设置

int towerh;  // 1st, never initialized nor assigned.
do{
    printf ("give me an integer between 1 and 23 and I will make a tower");
    int towerh = GetInt(); // 2nd, not the same object as the outer towerh

//      v----v        v----v  Uses the 1st towerh
}while (towerh < 1 || towerh > 23);

而只使用 1。

int towerh;  // One and only towerh
do{
    printf ("give me an integer between 1 and 23 and I will make a tower");
    // int towerh = GetInt();
    towerh = GetInt();
}while (towerh < 1 || towerh > 23);

【讨论】:

    猜你喜欢
    • 2020-07-07
    • 2021-10-14
    • 2011-06-19
    • 1970-01-01
    • 2013-08-30
    • 1970-01-01
    • 2011-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多