【问题标题】:Using an Array within a Function在函数中使用数组
【发布时间】:2013-12-03 04:05:10
【问题描述】:

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

【问题讨论】:

  • 您将一个整数而不是整数数组传递给favorites

标签: c++ arrays function


【解决方案1】:

将数组传递给函数时,不需要使用[] 运算符:

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) {
    ...
}

因为如果一个恶意的最终用户输入了五个,这个循环就不会停止。

【讨论】:

  • 谢谢,我现在感觉自己很笨。
【解决方案2】:

您正在呼叫favourites(sum[4])。这就是错误。它只发送索引为 4 的 sum 数组中的值。但是由于您需要整个数组,因此正确的语句是,

total = favourites(sum);

这将为您提供答案

【讨论】:

    【解决方案3】:

    我建议严格使用数组作为输入参数,如下所示。
    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 的东西。

    【讨论】:

      猜你喜欢
      • 2019-10-26
      • 2011-10-12
      • 2011-12-16
      • 2018-10-08
      • 2014-11-21
      • 2015-03-19
      • 1970-01-01
      • 1970-01-01
      • 2020-09-24
      相关资源
      最近更新 更多