C++ Complete this program using the following declarations, the TypeString array
ID: 3666931 • Letter: C
Question
C++
Complete this program using the following declarations, the TypeString array, and the main().
enum Type{Even, Odd};
union Value
{
int i;
double d;
};
struct Number
{
Type type;
Value value;
};
const string TypeString[2] = {"even","odd"};
int main()
{
Number var[10];
for (int i= 0; i < 10; i++)
assign(var[i]);
for (int i= 0; i < 10; i++)
print(var[i]);
}
You will need to add assign() and print() functions. The assign() function generates a random int between 0 and 99. If the int is odd, it is stored in the Value union and Odd in the Type. If the int is even, then store the square root of the random number is stored in the Value union and Even in the Type. The output from the print function should look like the following. Make use of the TypeString array in your print() function.
Number is odd 41
Number is odd 67
Number is even 5.83095
Number is even 0
Number is odd 69
Number is even 4.89898
Number is even 8.83176
Number is even 7.61577
Number is even 7.87401
Number is even 8
Explanation / Answer
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <cmath>
using namespace std;
enum Type{Even, Odd};
union Value
{
int i;
double d;
};
struct Number
{
Type type;
Value value;
};
const string TypeString[2] = {"even","odd"};
void assign(Number& val)
{
int r = rand()%100;
if(r%2==1)
{
val.type = Odd;
val.value.i = r;
}else
{
val.type = Even;
val.value.d = sqrt(r);
}
}
void print(Number val)
{
if(val.type==Odd)
cout<<"Number is "<<TypeString[1]<<" "<<val.value.i<<endl;
else
cout<<"Number is "<<TypeString[0]<<" "<<val.value.d<<endl;
}
int main()
{
srand(time(NULL));
Number var[10];
for (int i= 0; i < 10; i++)
assign(var[i]);
for (int i= 0; i < 10; i++)
print(var[i]);
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.