结构和阵列自动售货机

Structures and Arrays VendingMachine

本文关键字:自动售货机 阵列 结构      更新时间:2023-10-16

我不完全确定是什么使这种语法不正确,有什么答案吗?任务是编写一个模拟软饮料机的程序。程序应使用存储以下数据的结构。每次程序运行时,它都应进入执行以下步骤的循环:屏幕上会显示饮料清单。应该允许用户退出程序或选择饮料。如果用户选择饮料,他/她接下来将输入要插入饮料机的金额。程序应显示将返回的零钱量,并从机器中剩余的饮料数量中减去 1。 如果用户选择的饮料已售罄,则应显示一条消息。然后循环重复。

当用户选择退出程序时,它应该显示机器赚取的总金额。

饮料名称饮料费用
机器中的饮料数量

程序应创建一个包含五个结构的数组。

#include <iostream>
#include <string>
using namespace std;
struct VendItem {
    string drink_name;
    double cost;
    int amount;

};

int main()
{
    VendItem items[5];
    items[0] = { {"Cola", .75, 20} };        
    items[1] = { {"Rootbeer", .75, 20} };       
    items[2] = { {"Lemon-lime", .75, 20 } };     //These give me an error
    items[3] = { { "Grape Soda", .80, 20 } };    // What makes this wrong?
    items[4] = { { "Cream Soda", .80, 20 } };   
    for (int i = 0; i < 5; i++)
    {
        cout << items[i].drink_name << endl;
    }
    system("pause");
    return 0;
}
定义

变量时需要就地初始化数组,或者需要创建多个结构作为变量,然后赋值。

所以你可以这样做:

VedItem items[] = {
    { "Cola", .75, 20 },
    { "Rootbeer", .75, 20 }
    ...
};

或者你可以喜欢这个:

VendItem cola = { "Cola", .75, 20 };
VendItem rootbeer = { ... };
...
VendItem items[] = {
    cola,
    rootbeer,
    ...
};

或者像这样:

VendItem cola = { "Cola", .75, 20 };
VendItem rootbeer = { ... };
...
VendItem items[5];
items[0] = cola;
items[1] = rootbeer;
...

在一个不相关但非常重要的注意事项中,请记住数组索引从零到size - 1。因此,一个由五个元素组成的数组具有从 04(含(的索引。越界,例如在五个元素的数组中使用索引5(这是第六个索引(,将导致未定义的行为

这在您的循环中并不重要,因为您只能访问第二个元素,索引1 .

只要你有正确的数组,就有一个"技巧"来获取数组中的元素数量:

sizeof(items) / sizeof(items[0])

这将为您提供数组中的元素数量。但它仅适用于正确的数组。数组自然衰减为指向第一个元素的指针,例如,当您将数组传递给函数时,当您尝试在指针上执行上述技巧时,它将不起作用。对指针执行sizeof将返回实际指针的大小,而不是它指向的内容。因此,除非数组的大小在整个程序中都是已知的,否则在传递数组时,应始终将元素的数量作为参数传递给函数。

不需要双大括号,这样写:

VendItem items[5];
items[0] = { "Cola", .75, 20 };        
items[1] = { "Rootbeer", .75, 20 };       
items[2] = { "Lemon-lime", .75, 20 };     
items[3] = { "Grape Soda", .80, 20 };    
items[4] = { "Cream Soda", .80, 20 };