C++将数组转换为函数

C++ Turning arrays into functions?

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

我已经尝试了几个小时,但没有成功,正如你在我的代码中看到的那样,我有单独的函数,它们主要都在一起,但我需要将每个函数变成一个单独的函数。然而,当我尝试任何事情时,我都会出错,即使我试图传递参数。有人能给我指正确的方向吗?

#include <iostream>
#include <cstdlib>
#include <ctime>
void printarray();
void average();
void largestnumber();
using namespace std;
int main()
{
    printarray();
    average();
    largestnumber();
    }

void printarray() {
    srand(time(0));
    int n[10], tot = 0;
    for (int i = 0; i < 10; i++)
    {
        n[i] = (1 + rand() % 100);
        cout << n[i] << endl;
    }
}
void average() {
    int j, tot = 0, n[10];
    for (j = 0; j < 10; j++)
    {
        tot += n[j];
    }
    cout << "The average of the numbers in the array are " << tot / j << endl;
}
void largestnumber() {
    int w = 1, int n[10];
    int temp = n[0];
    while (w < 10)
    {
        if (temp < n[w])
            temp = n[w];
        w++;
    }
    cout << "The largest number in the array is " << temp << endl;
}

需要将处理的数组传递给每个函数,因此在任何地方都使用相同的数组。出于灵活性的原因,通过尺寸也是个好主意。

现在,您的函数在编写时基本上可以正常工作。

#include <iostream>
#include <cstdlib>
#include <ctime>
void printarray(int n[], size_t size);
void average(int n[], size_t size);
void largestnumber(int n[], size_t size);
using namespace std;
int main()
{
    const size_t arr_size = 10;
    int n[arr_size];
    printarray(n, arr_size);
    average(n, arr_size);
    largestnumber(n, arr_size);
}

void printarray(int n[], size_t size) {
    srand((unsigned int)time(0));
    int tot = 0;
    for (size_t i = 0; i < size; i++)
    {
        n[i] = (1 + rand() % 100);
        cout << n[i] << endl;
    }
}
void average(int n[], size_t size) {
    size_t j;
    int tot = 0;
    for (j = 0; j < size; j++)
    {
        tot += n[j];
    }
    cout << "The average of the numbers in the array are " << tot / j << endl;
}
void largestnumber(int n[], size_t size) {
    size_t w = 1;
    int temp = n[0];
    while (w < size)
    {
        if (temp < n[w])
            temp = n[w];
        w++;
    }
    cout << "The largest number in the array is " << temp << endl;
}

一个简单的改进是将printarray分解为initarray函数,该函数填充数组和打印内容的printarray。

对空数组之类的东西进行一些检查也是一个好主意(例如,函数假设n[0]存在)。

下一个显而易见的步骤是将所有这些放到一个类中。此外,如果允许的话,c数组应该替换为向量,因为这可以很好地将所有资源信息保持在一起。