In C++. Write a program to read the coefficients a , b , and c of a quadratic eq
ID: 3905632 • Letter: I
Question
In C++. Write a program to read the coefficients a, b, and c of a quadratic equation and print its roots, the values of x such that ax2 + bx + c = 0. The roots are given by: (-b ± ?b2 - 4ac)/2a
The discriminant is b2 - 4ac.
Make all of the variables of type double.
Create two functions, besides the main function. One function should return the positive root and the other the negative root of the quadratic formula.
Place the two function prototypes locally inside of the main( ) function, rather than globally.
Use local variables, rather than global variables
Put in a check to prevent division by zero.
Format your output to one decimal place.
Runs for the following input values:
Formulas a b c
1. x2 - x - 6 1.0 -1.0 -6.0
2. x2 - 15x 1.0 -15.0 0.0
3. x2 - 16 1.0 0.0 -16.0
4. 6x + 3 0.0 6.0 3.0
5. 3x2 + 3x - 6 3.0 3.0 -6.0
6. Optional special cases - if you include any of these in your program then you must submit a test run for each case showing that it works.
infinite solutions - a, b, and c are all 0
no solution - a and b are 0, but c is not 0 - (e.g.,, a, b, and c are 0, 0, 7)
one solution - the discriminant equals 0 - (e.g., 1, 2, 1)
complex solutions in the form a + bi - the discriminant is negative - (e.g., 1, -6, 13)
invalid character data
As before, part of your grade will be based on the proper use of:
1. meaningful variable names
2. indentation
3. blank lines and spacing
4. comments on the following:
- program description
- function descriptions
- all variable and constant declarations
- ambiguous or complex sections of code
5. the correct use of local variables, local function prototypes, and parameter passing
6. format and appearance of output
7. structured code (e.g., no goto, break (except in a switch), continue, etc. statements)
Explanation / Answer
Given below is the code for the question.
Please do rate the answer if it was helpful. Thank you
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int main()
{
double getRoot1(double a, double b, double c);
double getRoot2(double a, double b, double c);
double a, b, c;
double root1, root2;
cout << "Enter the value for a: ";
cin >> a;
cout << "Enter the value for b: ";
cin >> b;
cout << "Enter the value for c: ";
cin >> c;
root1 = getRoot1(a, b, c);
root2 = getRoot2(a, b, c);
cout << "Root 1: " << root1 << endl;
cout << "Root 2: " << root2 << endl;
}
double getRoot1(double a, double b, double c)
{
double discriminant = b * b - 4 * a * c;
double numerator = -b + sqrt(discriminant);
double denominator = 2 * a;
return numerator / denominator;
}
double getRoot2(double a, double b, double c)
{
double discriminant = b * b - 4 * a * c;
double numerator = -b - sqrt(discriminant);
double denominator = 2 * a;
return numerator / denominator;
}
output
=====
Enter the value for a: 1
Enter the value for b: -1
Enter the value for c: -6
Root 1: 3
Root 2: -2