Recently I've started to learn the C programming language. This is my first program which finds zero places of quadratic formulas. Doesn't parse, just gets the discriminants, counts delta and x1, x2.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void set_number_from_stdin(int *num, char* buf)
{
int final_number;
do
{
if (!fgets(buf, 1024, stdin))
{
// reading input failed
break;
}
final_number = atoi(buf);
} while (final_number == 0);
*num = final_number;
}
int main(void) {
int a, b, c, delta, deltaSqrt;
float x1, x2;
char buffer[1024];
printf("Quadratic Formula Calculator\n\n \
Given a function in normal form:\n \
f(x) = ax^2 + bx + c\n\n");
printf("Enter the `a` determinant: ");
set_number_from_stdin(&a, buffer);
printf("Enter the `b` determinent: ");
set_number_from_stdin(&b, buffer);
printf("Enter the `c` determinent: ");
set_number_from_stdin(&c, buffer);
printf("\n \
With given determinents:\n \
a = %d, b = %d, c = %d\n\n", a, b, c);
delta = b * b - 4 * a * c;
printf("The discriminator: %d \n", delta);
if (delta < 0)
{
printf("Zero places are not in the set of real numbers.\n");
}
else if (delta == 0)
{
x1 = (float) -b / (2 * a);
printf("Zero place: %.2f\n", x1);
}
else
{
deltaSqrt = sqrt(delta);
x1 = (float) (-b + deltaSqrt) / (2 * a);
x2 = (float) (-b - deltaSqrt) / (2 * a);
printf("Zero places: %.2f and %.2f\n", x1, x2);
}
return 0;
}
It's a really simple program, but I don't think I avoided some bugs, as I'm not experienced in languages like this.
Besides, I'm really in love with these pointers. I was scared at first, but when I would write a program in a high-level language, I would return a value from a function and then modify my variable, but not anymore. Now I can send a memory... sort of, ID number and modify its value inside my function. It's brilliant. :)
a
,b
,c
are coefficients, whereas discriminant (of a quadratic equation) specifically denotes the expression b²-4ac \$\endgroup\$