【问题标题】:My variables aren't working, keep recieving 'expression result unused' error我的变量不起作用,不断收到“未使用的表达式结果”错误
【发布时间】:2020-03-05 10:35:32
【问题描述】:

我目前正在做一个项目,该项目需要我制作一个由# 标记组成的右对齐三角形。我收到来自变量“空间”的错误。有人可以告诉我为什么会收到此错误吗?

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

int get_height(void);
int lineno;
int column_fill;
int main(void)
{
    int height = get_height();
    int space = height;
    for (lineno = 1; lineno <= height; lineno++ )
        {
        for (space; space > 0; space--)
            {
            printf(".");
            }
            for (column_fill = 1; column_fill <= lineno; column_fill++)
                {
                printf("#");
                }
            printf("\n");
            }
}

int get_height(void)
{
    int height;
    do
    {
        height = get_int("Height: ");
    }while(height < 0 || height > 9);

    return height;
}

我收到的错误是: mario.c:13:14:错误:表达式结果未使用 [-Werror,-Wunused-value] for (space; space > 0; space--) ^~~~~ 1 个错误生成。 : 目标“mario”的配方失败 make: *** [mario] 错误 1 ​​

【问题讨论】:

  • 如果您向我们提供包括行号在内的确切错误,将会有所帮助。是不是这个:for (space;?你打算这样做是什么?您的意思是将space 初始化为那里的某个值吗?我看到你在所有循环之外都有space = height;。但是内循环会更改space,并且当该循环在外循环的下一次迭代中再次运行时不会重置。
  • 我收到的错误是:mario.c:13:14: error: expression result used [-Werror,-Wunused-value] for (space; space > 0; space--) ^ ~~~~ 产生 1 个错误。 :目标“mario”的配方失败 make:*** [mario] 错误 1
  • 我要space=height来初始化space的起始值。然后,我希望 for 循环打印“。”数量 = 到“空间”,然后减少 1。
  • 抱歉,我是新手,不善于解释自己。
  • 欢迎来到 SO。作为对您未来问题的提示:请在问题中添加相关信息,例如您收到的错误消息。它们在 cmets 中几乎不可读。为此,您可以使用问题下方的edit 按钮更新您的问题并添加消息或任何其他附加信息。

标签: c variables cs50


【解决方案1】:

for (space; space &gt; 0; space--) 中,第一个space 不执行任何操作,编译器会就此发出警告。

通常,for 语句中的第一项是执行某些操作的表达式,例如赋值 space = height,或者是要在循环中使用的一个或多个对象的声明,例如 int space = height .将您的代码更改为其中之一,编译器将停止抱怨。

您可能应该使用后者并删除之前的 space 单独声明,因为:

  • 您需要在每次循环开始时重置space
  • 最好将声明保持在本地,以避免出错。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 2020-06-22
    • 2020-08-02
    • 2015-06-20
    • 1970-01-01
    相关资源
    最近更新 更多