将每个值传递给数组

时间:2014-08-16 09:13:19

标签: c++ arrays

我目前坚持将值存储到数组中。

以下是我的进展。我想将每个随机生成的数字存储到一个数组中。

我刚刚创建了一个新的函数原型,据说它应该读取每个生成的数字并存储在它的数组中。

#include<iostream>

using namespace std;

//Function prototype
void random(int val);
void store(int val1);


int main()
{
    int nvalue;
    cout << "How many numbers would you like to generate?\n";
    cin >> nvalue;//get input from user
    random(nvalue);//pass user input into random() function

    system("pause");
    return 0;
}

void random(int val)
{
    int num;//represent random integer output
    for (int i = 1; i < val; i++)//loop that will continue to generate integers based on n value from user
    {
        num = rand() % val + 1;//randomly generate number
        cout << "Num [" << i << "]" << "is " << num<<endl;
    }
}

1 个答案:

答案 0 :(得分:3)

这里是您需要的实施示例:

void random_store(int val, vector<int> &aVec);
int main()
{
   int nvalue;
   cout << "How many numbers would you like to generate?\n";
   cin >> nvalue;//get input from user

   vector<int> int_vector;
   random_store(nvalue, int_vector);//pass user input into random() function

   system("pause");
   return 0;
}
void random_store(int val, vector<int> &aVec)
{
   int num;//represent random integer output
   for (int i = 0; i < val; i++)
   {
      aVec.push_back(rand() % val + 1);
      cout << "Num [" << i << "]" << "is " << aVec[i] <<endl;
   }
}