在函数中使用数组

Using an Array within a Function

本文关键字:数组 函数      更新时间:2023-10-16

函数在收藏夹函数中查找条目总数的部分出现问题。编译器说我正在尝试将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的东西。