I've been trying to code a program that solves quadratic equations. Everything seemed fine to me, but the functions I try to go again didn't start after I'd called them. I can't understand what I made wrong.
#include <stdio.h>
#include <math.h>
int main(){
float a, b, c, delta, x1, x2;
char YN;
void enter(){
printf("Insert the value of 'a':\n");
scanf("%f", &a);
printf("Insert the value of 'b':\n");
scanf("%f", &b);
printf("Insert the value of 'c':\n");
scanf("%f", &c);
delta = (b*b) - (4 * a * c);
x1 = (-b-sqrt(delta))/(2*a);
x2 = (-b+sqrt(delta))/(2*a);
}
void solve(){
if (delta > 0){
printf("The first root of the equation is %f.", x1);
printf("The second root of the equation is %f.", x2);
}
else if (x1 == x2){
printf("The only root of the equation is %f.", x1);
}
else{
printf("The equation has no real roots.");
}
}
void input(){
scanf("%c", &YN);
}
void check(){
if (YN == 'Y'){
solve();
}
else if (YN == 'N'){
enter();
}
else {
input();
}
}
enter();
printf("Your equation must be: %f x^2 + %f x + %f, is it correct? Type Y for yes, N for no.\n", a, b, c);
input();
check();
return 0;
}
Because I thought the variables make the function not work, I tried having variables outside the solve function, but it didn't really work.
In standard C, you cannot define functions inside other functions. Instead, you must declare/define your functions separately outside of main()
.
Additionally, you can have global variables that can be accessed "globally" by all of your functions. They are not scoped to a specific function. To do this, declare them outside of your main function.
There are a few issues with this:
Here is an example of your code with the correct formatting:
#include <stdio.h>
#include <math.h>
// Function Declarations here
void enter();
void solve();
void input();
void check();
// Global Variables
float a, b, c, delta, x1, x2;
char YN;
int main(){
enter();
solve();
input();
check();
enter();
printf("Your equation must be: %f x^2 + %f x + %f, is it correct? Type Y
for yes, N for no.\n", a, b, c);
input();
check();
return 0;
}
// Function Definitions here
void enter(){
printf("Insert the value of 'a':\n");
scanf("%f", &a);
printf("Insert the value of 'b':\n");
scanf("%f", &b);
printf("Insert the value of 'c':\n");
scanf("%f", &c);
delta = (b*b) - (4 * a * c);
x1 = (-b-sqrt(delta))/(2*a);
x2 = (-b+sqrt(delta))/(2*a);
}
void solve(){
if (delta > 0){
printf("The first root of the equation is %f.", x1);
printf("The second root of the equation is %f.", x2);
}
else if (x1 == x2){
printf("The only root of the equation is %f.", x1);
}
else{
printf("The equation has no real roots.");
}
}
void input(){
scanf("%c", &YN);
}
void check(){
if (YN == 'Y'){
solve();
}
else if (YN == 'N'){
enter();
}
else {
input();
}
}