在函数中使用数组
Using an Array within a Function
函数在收藏夹函数中查找条目总数的部分出现问题。编译器说我正在尝试将int转换为int*。我似乎不明白为什么它认为我试图将数组转换为整数。
#include <iostream>
using namespace std;
enum DrinksType {COKE, PEPSI, SPRITE, DR_PEPPER};
int favorites(int sum[]);
void Prompt();
int main ()
{
int sums[4];
int number;
int total;
DrinksType index;
for (index = COKE; index <= DR_PEPPER; index = DrinksType(index+1))
sums[index] = 0;
Prompt();
cin >> number;
while (number != 4)
{
switch(number)
{
case 0:
sums[0]++;
break;
case 1:
sums[1]++;
break;
case 2:
sums[2]++;
break;
case 3:
sums[3]++;
break;
}
Prompt();
cin >> number;
}
total = favorites (sums[4]);
cout << "Coke: " << sums[0] << endl;
cout << "Pepsi: " << sums[1] << endl;
cout << "Sprite: " << sums[2] << endl;
cout << "Dr. Pepper: " << sums[3] << endl;
cout << "The number of responses is: " << total;
return 0;
}
//*******************************************************
void Prompt()
{
cout << "Enter a 0 if your favorite is a Coke." << endl;
cout << "Enter a 1 if your favorite is a Pepsi." << endl;
cout << "Enter a 2 if your favorite is a Sprite." << endl;
cout << "Enter a 3 if your favorite is a Dr. Pepper." << endl;
cout << "Enter a 4 if you wish to quit the survey." << endl;
}
int favorites (int sum[])
{
int total = 0;
for (int i = 0; i<4; i++)
total = total + sum[i];
return total;
}
将数组传递给函数时,不需要使用[]
运算符:
total = favorites(sums); // not sums[4]
方括号从一个整数数组中取一个整数,所以编译器在抱怨。
注意:这段代码
switch(number)
{
case 0:
sums[0]++;
break;
case 1:
sums[1]++;
break;
case 2:
sums[2]++;
break;
case 3:
sums[3]++;
break;
}
可以缩短为一行:
sums[number]++; // Yes, that's it :)
最后,在进入这个循环之前,您应该检查用户输入:
while (number != 4) {
...
}
因为如果恶意的最终用户输入5,这个循环将不会停止。
您正在调用favourites(sum[4])
。这就是错误。它只发送索引为4的sum数组中的值。但既然你需要整个数组,正确的说法是,
total = favourites(sum);
这将为您提供答案
我建议严格使用数组作为输入参数,如下所示
在int
之前添加或删除const
取决于您的需要。
template <size_t size>
void Function1(const int (&input)[size])
{
for (int i = 0; i < size; ++i)
{
std::cout << input[i] << std::endl;
}
}
如果你的数组是固定大小的,那么你可以去掉template
的东西。
相关文章:
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 打印 2D 动态数组 c++ 函数
- C++数组函数
- 在数组函数指针中调用void
- 数组函数似乎没有找到最大值
- 使用数组函数和循环求解伪元编码|C
- 在头文件中的函数原型中获取指针数组:函数声明为 void
- 数组函数错误输出
- 读取文件,然后创建数组函数C++
- 指针数组函数参数-奇怪的行为
- 二维数组 - 函数
- "return"没有从数组函数返回正确的值
- 数组函数问题
- 数组函数的大小返回 int 的大小而不是数组
- 从数组函数中删除元素
- 如何从C++中最好地调用具有C99风格数组函数签名的函数
- 追加/打印/插入数组c++函数问题
- 如何将数组函数转换为指针函数
- 多维数组函数输出垃圾
- C++:数组函数的递归最大值