This code is supposed to randomly assign numbers to an array of structs, but isn't working at all.
I have no clue why, everything looks fine to me, can some one take a look and tell me why it's crapping out on me?
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
enum Type{Even, Odd};
const string TypeString[2] = {"even","odd"};
// ------ Structures ---------------------------------------------
union Value
{
int i;
double d;
};
struct Number
{
Type type;
Value value;
};
// ------ Prototypes ---------------------------------------------
Number assign(Number);
void print(Number);
// ****** MAIN ***************************************************
int main()
{
// srand(time(0));
Number var[10];
for (int i = 0; i < 10; i++)
assign(var[i]);
for (int i = 0; i < 10; i++)
print(var[i]);
for (int i = 0; i < 10; i++)
cout << var[i].value.d << endl;
return 0;
}
// ****** FUNCTION: Print ****************************************
//
//****************************************************************
void print(Number input)
{
if(input.type == Even)
{
cout << "The number is " << TypeString[input.type] << " " << input.value.i << endl;
}
else if(input.type == Odd)
{
cout << "The number is " << TypeString[input.type] << " " <<input.value.d << endl;
}
return;
}
// ****** FUNCTION: Assign ***************************************
//
//****************************************************************
Number assign(Number input)
{
int num;
num = rand() % 10 + 1;
if(num % 2 == 0)
{
input.type = Even;
input.value.i = num;
}
else if(num % 2 != 0)
{
input.type = Odd;
input.value.d =num;
}
return input;
}
Ouput
The number is even 2686652
The number is even 4286736
Process returned 0 (0x0) execution time : 0.062 s
Press any key to continue.
As you can see, it's only printing twice instead of 10 times, and the numbers are way nutz. Also, I'm using srand, but getting the same values everytime it runs.