简体   繁体   中英

Trouble returning an array value

I keep getting an error code saying jeb has redefined itself and changing int to float or double doesn't work. This is meant to be a random number generator and my array is messing up.

#include "stdafx.h"
#include <iostream>
#include <random>

using std::cout;
using std::endl;
using std::cin;

int generate();
int numb();

int main()
{
    int num = numb();
    cout << num << endl;
    cout << endl;

    int gen = generate();
    cout << gen << endl;
    cout << endl;
    system("Pause");
    return 0;
}

int generate(float *jeb[])
{
    int jeb [20] = {};
    for (int i = 0; i < 20; i++) {
        int rng = rand() % numb() + 1;
        jeb[i] = rng;
        return jeb;
    }
}

int numb()
{
    int choice;
    cout << "Enter maximum number: ";
    cin >> choice;
    return choice;
}

There are several problems here:

int generate(int *jeb[])
{
    int jeb [20] = {};
//...
}

Now you have two things called jeb . Let's assume you just want one. You could send in a pointer and fill it up

int generate(int *jeb)
{
//.. fill it up in a for loop
}

BUT this says it returns an int...

Instead of pointers, try using an array - you seem to know in advance you have 20 elements:

#include <array>

std::array<int, 20> generate()
{
    std::array<int, 20> jeb;
    for (int i = 0; i < 20; i++) {
        int rng = rand() % numb() + 1;
        jeb[i] = rng;
        return jeb; //Really, wait - we haven't done the whole loop yet
    }
}

Another issue might now be obvious: you are returning in the middle of the for loop. Wait until you've finished generating what you need.

std::array<int, 20> generate()
{
    std::array<int, 20> jeb;
    for (int i = 0; i < 20; i++) {
        int rng = rand() % numb() + 1;
        jeb[i] = rng;
    }
    return jeb; // loop now done
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM