Kar Keng Chan - 11 months ago 47

C Question

I'm new to C language and coding and I encountered a question asking me to change the function header of:

`float RealRoot_1(float a, float b, float c);`

float RealRoot_2(float a,float b,float c);

to become:

`void RealRoot_1(void);`

void RealRoot_2(void);

I was told that it has something to do with Global Variables but I still couldn't figure it out after trying quite some time. Can anyone please explain on how to do it? Thanks a lot.

The source file is as below:

`#include<stdio.h>`

#include<math.h>

int main()

{

float RealRoot_1(float a, float b, float c); // Prototype declaration

float RealRoot_2(float a, float b, float c);

// Defining Input Variables

float x, y, z;

// Defining Output Variables

float Root_1, Root_2;

printf("Please enter the factor of X^2: ");

scanf("%f",&x);

printf("Please enter the factor of X: ");

scanf("%f",&y);

printf("Please enter the free factor: ");

scanf("%f",&z);

Root_1 = RealRoot_1(x,y,z);

Root_2 = RealRoot_2(x,y,z);

printf("the First Root is: %f \n", Root_1);

printf("the Second Root is: %f \n", Root_2);

system("pause");

}

float RealRoot_1(float a, float b, float c)

{

float x;

x = (-1*b + sqrt(pow(b,2) - 4 * a * c)) / (2 * a);

return x;

}

float RealRoot_2(float a, float b, float c)

{

float x;

x = (-1*b - sqrt(pow(b,2) - 4 * a * c)) / (2 * a);

return x;

}

Answer Source

This can be done by using global variables. You need to ensure that the variable names used in the function are the same as the ones used in the main code.

```
#include<stdio.h>
#include<math.h>
void RealRoot_1(void); // Prototype declaration
void RealRoot_2(void);
float x, y, z;
float Root_1, Root_2;
int main()
{
// Defining Output Variables
printf("Please enter the factor of X^2: ");
scanf("%f",&x);
printf("Please enter the factor of X: ");
scanf("%f",&y);
printf("Please enter the free factor: ");
scanf("%f",&z);
RealRoot_1();
RealRoot_2();
printf("the First Root is: %f \n", Root_1);
printf("the Second Root is: %f \n", Root_2);
system("pause");
}
void RealRoot_1(void)
{
Root_1 = (-1*y + sqrt(pow(y,2) - 4 * x * z)) / (2 * x);
}
void RealRoot_2(void)
{
Root_2 = (-1*y - sqrt(pow(y,2) - 4 * x * z)) / (2 * x);
}
```

**Please note** that this is a worse way of doing things than was given in the initial problem. In the initial exercise. You are loosing modularity and using too many globals is in general a bad idea.

You can also see Are global variables bad?