C++ C++;将数组转换为函数?
我已经尝试了几个小时,但没有任何效果,正如您在我的代码中看到的,我有单独的函数,它们主要都在一起,但我需要将每个函数转换为单独的函数。然而,当我尝试任何事情时,我都会出错,甚至当我尝试传递参数时也是如此。有人能给我指出正确的方向吗C++ C++;将数组转换为函数?,c++,C++,我已经尝试了几个小时,但没有任何效果,正如您在我的代码中看到的,我有单独的函数,它们主要都在一起,但我需要将每个函数转换为单独的函数。然而,当我尝试任何事情时,我都会出错,甚至当我尝试传递参数时也是如此。有人能给我指出正确的方向吗 #include <iostream> #include <cstdlib> #include <ctime> void printarray(); void average(); void largestnumber(); usi
#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;
}
#包括
#包括
#包括
void printary();
无效平均值();
void largestnumber();
使用名称空间std;
int main()
{
printarray();
平均值();
最大数();
}
void printary(){
srand(时间(0));
int n[10],tot=0;
对于(int i=0;i<10;i++)
{
n[i]=(1+rand()%100);
cout您正在使用的数组需要传递给每个函数,因此在任何地方都使用相同的数组。出于灵活性的原因,传递大小也是一个好主意
现在,您的函数在编写它们的过程中基本正常工作
#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;
}
#包括
#包括
#包括
void printary(int n[],size\u t size);
空隙平均值(整数n[],大小\u t大小);
最大无效数(整数n[],大小\u t大小);
使用名称空间std;
int main()
{
常数大小=10;
int n[arr_size];
打印阵列(n,阵列大小);
平均值(n,arr_大小);
最大数量(n,arr_大小);
}
无效打印数组(int n[],大小\u t大小){
srand((无符号整数)时间(0));
int-tot=0;
对于(大小i=0;i 请在printarray()、average()和largestnumber()中写出您尝试过的内容和出现的错误函数声明一个数组n
。如果不初始化该数组的内容,则立即继续使用该数组中的值。由于该数组未初始化,这将成为未定义的行为,由此产生的结果将随机生成。