c++的动态数组最大值

用new运算符动态分配一个长度为n的整型数组(n值由键盘输入),并给该数组随机赋上100以内的整数,输出数组。定义函数求数组的最大值,最大值由参数带回,(提示:可用指针参数或引用参数带回最大值,对比二者的区别)。调用求数组内最大值的这个函数,并输出最大值,最后删除所申请空间。

#include <iostream>
#include <math.h>
#include <time.h>
using namespace std;
void getmax(int *a,int n,int &max)
{
    max = a[0];
    for(int i=1;i<n;i++)
        if(max < a[i])
            max = a[i];
}
 
int main()
{
    srand(time(NULL));
    int n;
    cin>>n;
    int *a = new int[n];
    for(int i=0;i<n;i++)
    {
        a[i] = rand()%100;
        cout<<a[i]<<endl;
    }
    int max = 0;
    getmax(a,n,max);
    cout<<"max="<<max<<endl;
    delete []a;
    return 0;
}


#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

// 求取整型数组的最大值,使用指针参数
int getMax(int* arr, int len) {
    int maxVal = arr[0];
    for (int i = 1; i < len; i++) {
        if (arr[i] > maxVal) {
            maxVal = arr[i];
        }
    }
    return maxVal;
}

int main() {
    int n;
    cout << "请输入数组长度n:";
    cin >> n;

    // 动态分配数组空间
    int* arr = new int[n];

    // 随机赋值
    srand(time(nullptr));
    for (int i = 0; i < n; i++) {
        arr[i] = rand() % 100;
    }

    // 输出数组
    cout << "生成的随机数组为:[ ";
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
    cout << "]" << endl;

    // 求取最大值
    int maxVal = getMax(arr, n);

    // 输出最大值
    cout << "数组中的最大值为:" << maxVal << endl;

    // 释放数组空间
    delete[] arr;

    return 0;
}

上述代码中,首先使用new运算符动态分配了一个长度为n的整型数组,并使用rand函数给数组中的每个元素赋了一个100以内的随机值。然后,定义了一个名为getMax的函数,该函数的作用是求取整型数组的最大值,并使用指针参数将最大值返回。在main函数中,调用了getMax函数来求取数组的最大值,并将结果输出。最后,使用delete运算符释放了动态分配的数组空间。

不知道你这个问题是否已经解决, 如果还没有解决的话:

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^