Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Input: from the user Output: standard output AND file named \"program3.txt\" Wri

ID: 3870856 • Letter: I

Question

Input: from the user

Output: standard output AND file named "program3.txt"

Write a program that will calculate both roots of a quadratic equation. The program should ask the user to input a, b, and c and then write both roots to standard output (the screen) and a file named "program3.txt". Your program should print the roots ordered from least to greatest. If the quadratic equation has a negative discriminant your program should output "NO REAL ROOTS". If the two roots are the same only report one root

Explanation / Answer

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

//Main method definition
int main ()
{
//To store a, b, and c value
double a;
double b;
double c;

//To store determinant
double determinant;

//To store first and second root
double rootOne, rootTwo;

//To store root number
int numRoots;

//FILE pointer declares to write on the file
FILE *fw;

//Opens the file for writing
fw = fopen("E:/TODAY/program3.txt", "w");

if(fw == NULL)
{
printf("Error! Unable to open the file");
exit(1);
}
//Accepts a, b and c value
printf("Enter a,b,c: ");
scanf("%lf %lf %lf", &a, &b, &c);

//Displays a, b, and c value
printf(" a = %lf b = %lf c = %lf", a, b, c);

// If a = 0, it is not a quadratic equation
if (a == 0 || b == 0 || c == 0)
{
printf("Error: Roots cannot be determined");
exit(1);
}//End of if

//Calculates determinant
determinant = pow(b, 2.0) - 4.0 * a * c;

//Calculates root one
rootOne = ((-b) - sqrt(determinant))/(2.0 * a);

//Calculates root two
rootTwo = ((-b) + sqrt(determinant)) / (2.0 * a);

//Checks if determinant is less than zero or negative display no real root
if(determinant < 0)
{
printf(" No real root");
//Writes data to file
fprintf(fw, "No real root");
}//End of if
//Checks if both the roots are equal display root one
else if(rootOne == rootTwo)
{
printf("%lf", rootOne);
//Writes rootOne data to file
fprintf(fw, "Root rootOne);
}//End of else if
//Otherwise display both the roots
else
{
printf(" Root one: %lf Root two: %lf", rootOne, rootTwo);
//Writes root one and root two to file
fprintf(fw, "Root Root Two = %lf", rootOne, rootTwo);
}//End of else
//Close file
fclose(fw);
return 0;
}//End of main

Sample Run1:

Enter a,b,c: 2
3
4

a = 2.000000 b = 3.000000 c = 4.000000
No real root

Sample Run 2:

Enter a,b,c: 3
12
1

a = 3.000000 b = 12.000000 c = 1.000000
Root one: -3.914854 Root two: -0.085146