Bartlomiej Mlynarkiewicz - 10 months ago 66

C Question

My professor told us to write a c program which solves quadratic equations but he added that at the start he wants us to define 4 sets of 3 coefficients for each a, b and c. So in other words I have to define 4 sets of 3 different coefficients for each a, b, and c and once the program solves the equation for the 1st set of 3 coefficients for a,b and c its to proceed and solve the next set of 3 defined coefficients until all 4 sets are solved.

I am able to write a program that solves the quadratic equation by defining each a,b and c coefficient individual using scanf. Can you please help, as I can't find the answer anywhere?

Thats what I have written so far, its pretty simple but it works. I'm in an engineering course and we only have 2hrs a week of labs which dont reflect the lectures.

`#include <stdio.h>`

#include <math.h>

#include <string.h>

double a,b,c, root1, root2, discriminant, realpart, imaginarypart;

char anwser;

char x [100] = "Are your choices correct ? Y /N ";

int main ()

{

start:

printf("Enter your coefficient for a : ");

scanf("%lf",&a);

printf("Enter your coefficient for b : ");

scanf("%lf",&b);

printf("Enter your coefficient for c : ");

scanf("%lf",&c);

printf("Your coefficients are : \na = %lf\nb = %lf\nc = %lf\n",a,b,c);

printf("%s",x );

scanf("%s",&anwser);

if (!strcmp(&anwser, "N"))

{

printf("Enter your coefficients again\n");

goto start;

}

discriminant = (b*b - 4*a*c);

root1 = (-b - sqrt(discriminant)) / (2*a);

root2 = (-b + sqrt(discriminant)) / (2*a);

if (discriminant > 0 )

{

printf("root1 = %lf\nroot2 = %lf\n", root1, root2);

}

else if (discriminant == 0)

{

printf("root1 = root2 = %lf\n",root1);

}

else

{

realpart = -b/(2*a);

imaginarypart = sqrt(-discriminant)/(2*a);

printf("root1 = %lf + %lfi\nroot2 = %lf - %lfi\n",realpart, imaginarypart, realpart, imaginarypart);

}

}

Answer Source

You mix 2 things: *defining* 4 sets and *reading them from input* (as I understood from your "using `scanf`

").

(Reading them from input makes no problem as new read values overwrite old.)

*Defining* 4 sets in advance may be simply done by *arrays*:

```
float as[4], bs[4], cs[4]; // as[0], bs[0], cs[0] is the 1st set, etc.
float a , b , c ;
// Assigning values to sets: as[0] = ...; bs[0] = ..., cs[0] = ...;
as[1] = ...; bs[1] = ..., cs[1] = ...;
......................................
......................................
// or initialize them directly in the previous declaration, e.g.
// float as[] = {1, 4, -2, 3},
// bs[] = {0, 5, 1, -1},
// cs[] = {2, -4, 1, 2};
for (int i; i < 4; ++i)
{
a = a[i];
b = b[i];
c = c[i];
// Code (or a function call) for computing and printing result(s) from a, b, c
}
```