【问题标题】:book[] in if statement errorbook[] in if 语句错误
【发布时间】:2017-08-14 02:11:01
【问题描述】:
void displayInventory(const struct Book book[], const int size) {

Idk y book[] 在 Visual Studio 中遇到错误请帮助。

if (book[] < 0) {
    printf("The inventory is empty!");
    printf("===================================================");
}
else {
    printf("Inventory\n");
    printf("===================================================\n");
    printf("ISBN      Title               Year Price  Quantity\n");
    printf("---------+-------------------+----+-------+--------");
    printf("%-10.0d%-20s%-5d$%-8.2f%-8d", book[]._isbn, book[]._title, book[]._year, book[]._price, book[]._qty);
}
}

【问题讨论】:

  • 你必须指定 book[some_index] 值来检查..
  • 您只能在变量定义中使用空的[](通常在函数参数列表中;还有一些其他相关的上下文可以出现)。在if (book[booknumber].isbn &lt; 0) 之类的引用中,您必须提供下标(我在这里使用了booknumber;我可能会在程序中使用较短的名称)。
  • 另请注意,您不应创建以下划线开头的名称。如果你足够了解不需要问这个问题,你也许可以引用确切的规则,但是当你需要问这样的问题时,规则很简单:不要以下划线开头 - 尽管你看到的任何先例。大多数这样的名称是为实现而保留的。您可能不会立即遇到问题,但它可能会在以后再次出现并伤害您。
  • 这就是老师想要的,但是我现在明白了,谢谢你的帮助
  • 您希望这行:(book[] &lt; 0) 评估为什么?请记住,book[] 是一个指针。指针是无符号的(在大多数情况下),所以表达式是说:'这个指针是否小于 0' 可能不是你想问的

标签: c function if-statement struct


【解决方案1】:

book 变量是Struct Book 项的数组。如果你想访问其中的一个,你需要提供它的索引,例如:

if (book[0].id == 7) ...

在您的情况下(检查库存),您可能想要使用传入的大小(假设这是正在使用的项目数而不是数组的大小 - 这可能是在这种情况下应该是什么,因为有清单列表者无需知道实际数组本身的大小,只需知道您要显示的项目数):

if (size <= 0) // inventory is empty.

把这些两个放在一起,你最终可能会得到类似的东西:

void displayInventory (const struct Book book[], const int size) {
    if (size <= 0) {
        puts ("The inventory is empty!");
        puts ("======================================================");
        return;
    }
    puts ("Inventory");
    puts ("=======================================================");
    puts ("ISBN       Title                Year  Price    Quantity");
    puts ("----------+--------------------+-----+--------+--------");
    for (int idx = 0; idx < size; idx++) {
        printf ("%-10.0d %-20s %-5d$ %-8.2f %-8d\n",
            book[idx]._isbn, book[idx]._title, book[idx]._year,
            book[idx]._price, book[idx]._qty);
    }
}

【讨论】:

    猜你喜欢
    • 2017-04-28
    • 1970-01-01
    • 2021-08-06
    • 2011-09-22
    • 1970-01-01
    • 2017-04-07
    • 2017-05-04
    • 2017-05-29
    • 2014-06-20
    相关资源
    最近更新 更多