【问题标题】:Can't define a variable无法定义变量
【发布时间】:2016-09-26 06:55:20
【问题描述】:

当我尝试声明任何类型的变量并为其赋值时,编译器会引发“未使用的变量错误”。下面我使用'float'作为变量类型并尝试将其分配给1.5。

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

int main(void)
{
    printf("How long is your shower?\n");
    int time = GetInt();

    float flow = 1.5;
}

编译器抛出此错误:

~/workspace/pset1/ $ make water
clang -ggdb3 -O0 -std=c11 -Wall -Werror -Wshadow    water.c  -lcs50 -lm -o water
water.c:10:11: error: unused variable 'flow' [-Werror,-Wunused-variable]
    float flow = 1.5;
          ^
1 error generated.
make: *** [water] Error 1

【问题讨论】:

  • 看来这个问题在这里已经解释过了:enter link description here
  • #include &lt;cs50.h&gt; 不是 C 的一部分,未显示,也未涉及您的问题。您想从示例代码中删除它。

标签: c variables cs50


【解决方案1】:

flow 未被您的程序使用 - 它不涉及任何副作用,您只需为其赋值并丢弃它。好的编译器会警告此类未使用的变量。

通过使用-Werror,您将警告变成了错误。

【讨论】:

    【解决方案2】:

    这实际上是一个警告而不是错误,但由于 -Werror 标志,您将其视为错误。

    长话短说,如果您使用该变量,它将不再返回错误。

    #include <stdio.h>
    #include <cs50.h>
    
    int main(void)
    
    {
        printf("How long is your shower?\n");
        int time = GetInt();
    
        float flow = 1.5;
        printf("Flow: %.2f, time: %d", flow, time);
    }
    

    【讨论】:

    • 但现在它会警告time 变量:ideone.com/Dzkjix
    • @mch:很公平,我也将那个添加到了 print 语句中:)
    【解决方案3】:

    似乎合法,您没有在任何地方使用该变量。打印出来试试;

    printf("%.2f", flow);
    

    【讨论】:

      猜你喜欢
      • 2021-05-10
      • 2014-12-01
      • 2014-03-21
      • 2022-01-04
      • 2015-05-01
      • 1970-01-01
      • 2020-05-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多