返回处理数组的int函数

时间:2017-05-06 21:40:30

标签: c++ c++11 visual-c++

我是c ++的新手,还没有完全掌握功能的概念。我写的这段代码应该得到一个数组并显示数组,最高数字和最低数字。一切正常,除了显示最低和最高。我很困惑如何返回这些值并显示它们。

int find_highest(int array[], int size)
    {
        int count;
        int highest1;
        highest1 = array[0];
        for (count = 1; count < size; count++)
        {
            if (array[count] > highest1)
                highest1 = array[count];
        }
        cout << "The highest values is: " << highest1 << endl;
    }

1 个答案:

答案 0 :(得分:1)

具有返回值的函数必须通过return关键字将其传递出去。例如你找到了最高的:

int find_highest(int array[], int size)
{
    int count;
    int highest1;
    highest1 = array[0];
    for (count = 1; count < size; count++)
    {
        if (array[count] > highest1)
            highest1 = array[count];
    }

    // replace the cout with a return:  
    // cout << "The highest values is: " << highest1 << endl;
    return highest1; 
}

请注意,当命中返回时,函数总是结束,所以如果你有一个带有单独分支的函数,每个分支都带有一个return语句,那些函数表示函数退出的位置(它有更好的形式但是有一个返回如果可能的话,指向底部,特别是对于大而复杂的功能)。

现在,你在调用函数中创建一个变量来保存返回的值,你现在可以在main中使用它:

int highest = find_highest(array, ten_values);
cout << "The highest values is: " << highest << endl;

或者你可以直接从打印命令中调用该函数,如果你不需要使用最高的其他任何东西:

cout << "The highest value is: " << find_highest(array, ten_values) << endl;
相关问题