-4

Not sure why this is not working. I have not used return very much but was wondering why it is returning zero.

using namespace std;
void randgen(int &y);
int doub(int y);

int main()
{
int y, num;

randgen(y);
cout<<num<<endl;
}

void randgen(int y)
{
unsigned seed = time(0);
srand(seed);

y = (rand() % (99-10+1))+10;
num = y;
return num;

}
NSbrian
  • 1
  • 1

2 Answers2

0

In main, you declare a variable named num which is local to the main function. You never pass it as an argument to the randgen function. However, you print it in your main function. When you print num in your main function, it is not printing the num variable from the randgen function, but the num variable from the main function. In fact, you don't really need num. You can just return y from the randgen function. You should also set your call to randgen to a variable before you use cout or just use cout << randgen(y) << endl;

If you're returning a value from your randgen function, you need to change it from void to whatever data type your returning. You also cannot use num in randgen because it is not declared. You must declare a variable before you can use it.

Hope this helps!

Lelia
  • 1
-1

num is never assigned any value in main(). Instead of just randgen(y); you need num = randgen( y );

randgen() is declared as void - if you want to return something (a random integer in this case) you need to declare it as such.

You're passing y as a parameter to randgen() before it is assigned any value. So you need to assign something to it. (Another question is that you never use the value y in randgen() itself, so why pass it in the first place...)

There is no need to assign the generated value to y then num then return that (besides num not being declared in the function at all) you can just return the generated value.

These are probably the main issues. With all that, here's the version of the code that works and does what you (presumably) want.

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int randgen(int y);

int main()
{
int y, num;
y = 5;
num = randgen(y);
cout<<num<<endl;
}

int randgen(int y)
{
unsigned seed = time(0);
srand(seed);

return (rand() % 90)+10;
}
Peter Szoldan
  • 4,792
  • 1
  • 14
  • 24