Union as status parameter in C
Today's problem is on the declaration of a union structure with members of all datatypes. When program computes a problem, it updates the union members and shows the output exactly in the same format, as the union members were updated.
I wrote a C program for the same problem. The C codes are given below:
#include <stdio.h>
#include <string.h>
union out {
int ansi; //for integer type answer
float ansf; //for float type answer
double ansd; //for double type answer
char *anss; //for char type answer
};
void outv(union out *s, int i) { //output function
if (i == 0 || i == 1) //convert all numeric data into double type
printf("%lf\n", s->ansd);
if (i == 3) //for string type output
printf("%s\n", s->anss);
return;
}
int main() {
union out o;
double i = 0, j = 0;
double ans;
printf("Enter two space separated numbers : ");
scanf("%lf", &i);
scanf("%lf", &j);
if (i == 0 && j == 0) { //check all numbers should not be zeros
o.anss = "All number are zero. Not Accepted.";
outv(&o, 3); //push string output
return 0;
}
ans = i + j;
o.ansd = ans;
outv(&o, 0); //push numeric output
if (j == 0) { //check whether denominator is zero
o.anss = "Division by zero. Not Accepted.";
outv(&o, 3); //push string output
return 0;
}
ans = i / j;
o.ansd = ans;
outv(&o, 1); //push numeric output
return 0;
}