结构和阵列自动售货机
Structures and Arrays VendingMachine
我不完全确定是什么使这种语法不正确,有什么答案吗?任务是编写一个模拟软饮料机的程序。程序应使用存储以下数据的结构。每次程序运行时,它都应进入执行以下步骤的循环:屏幕上会显示饮料清单。应该允许用户退出程序或选择饮料。如果用户选择饮料,他/她接下来将输入要插入饮料机的金额。程序应显示将返回的零钱量,并从机器中剩余的饮料数量中减去 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
。因此,一个由五个元素组成的数组具有从 0
到 4
(含(的索引。越界,例如在五个元素的数组中使用索引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 };
相关文章:
- OpenMP阵列性能较差
- 'short int'持有的值溢出,但"自动"不会溢出?
- 如何将三维尺寸不固定的三维阵列展平为一维阵列
- 当我的阵列太大时出现分段错误
- 普通环路未使用gcc 4.8.5自动矢量化
- 为什么这个 c++ 代码打印出长度 5,当我打印出字符串时,程序会自动终止?
- QwtPlot具有相等的轴和自动缩放
- 位阵列上的快速AND运算
- 如何进行自动阵列检测?
- 唯一/共享 ptr 用于在数组超出范围后自动删除阵列
- C 自动售货机程序,具有C
- 如何自动并行化堆阵列
- C :自动变量扣除额的范围与循环的范围与多维阵列的循环的正常范围
- 循环时,如何在C 中创建一个自动插入阵列
- 自动售货机程序(帮助)
- 结构和阵列自动售货机
- 如何跟踪自动售货机中可用硬币的硬币编号
- 自动售货机项目
- 自动释放阵列
- 错误 C2504:"自动售货机":未定义基类