【问题标题】:c++ array arguments not workingc ++数组参数不起作用
【发布时间】:2017-05-14 00:36:19
【问题描述】:

我正在尝试创建一个函数来查找任何数组的最大值,并且由于某种原因该函数不会将数组作为输入(它适用于运行非常大的数字的程序,如无符号长整数)。

 #include <iostream>
using namespace std;

int findMax();

int main(){
int test[6] = {1,2,3,4,5,6};
findMax(test,6);//Says invalid arguments


return 0;
}

int findMax(int x[],unsigned long int size){
    unsigned long int max = 0;
    unsigned long int newmax = 0;
    for(int i = 0; i < size; i++ ){
        x[i] = newmax;
        if(newmax > max) max = newmax;
    }
    return max;
}

我做错了什么?另外,请随意判断它有什么问题。

【问题讨论】:

    标签: c++ arrays function parameters


    【解决方案1】:

    你的原型应该和函数定义一致如下:

    int findMax(int [], unsigned long int );
    

    另外,你可以按如下方式压缩你的函数:

    int findMax(int x[],unsigned long int size)
    {
        unsigned long int max = x[0];
    
        for(int i = 1; i < size; i++ )
            if(x[i] > max) max = x[i];
    
        return max;
    }
    

    最后,你需要使用从函数返回的值,这样你就可以在 main 中编写:

    cout << findMax(test,6);
    

    而不仅仅是函数。

    【讨论】:

    • 是的,我知道返回值必须去某个地方,但它是原型。感谢您的压缩建议
    【解决方案2】:

    当您为findMax 编写前向声明时,您声称它没有参数,但随后您用一些参数调用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-24
      • 2019-09-15
      • 2015-05-23
      • 1970-01-01
      • 2012-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多