SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,julia Lobur
Chapter:
More Flow Of Control
Exercise:
Programming Projects
Question:6 | ISBN:9780321531346 | Edition: 7

Question

(This Project requires that you know some basic facts about complex numbers; so, it is only appropriate if you have studied complex numbers in some mathematics class.) Write a C++ program that solves quadratic equation to find its roots. The roots of a quadratic equation ax^2 + bx + c = 0

(where a is not zero) are given by the formula:

(–b } sqrt(b2 – 4ac)) / 2a

The value of the discriminant (b2 – 4ac) determines the nature of roots. If the value of the discriminant is zero then the equation has a single real root. If the value of the discriminant is positive then the equation has two real roots. If the value of the discriminant is negative, then the equation has two complex roots.

The program takes values of a, b, and c as input and outputs the roots. Be creative in how you output complex roots. Include a loop that allows the user to repeat this calculation for new input values until the user says she or he wants to end the program.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Program code:

#include<iostream>
#include<cmath>
using namespace std;
void main()
{
	int a, b, c;
	double d;
	char choice;
	do	
	{
cout<<" Quadratic equation form: ax^2 +bx+c = 0"
<<endl;
		cout<<" Enter a:";
		cin>>a;
		cout<<" Enter b:";
		cin>>b;
		cout<<" Enter c:";
		cin>>c;
		d = (b*b - 4*a*c);
		if(d== 0)
		{	
			cout<<"Root of equation is: "<<-b/a<<endl;
		}
		else if(d>0)
		{   
			cout<<"Roots of equation are: "
				<<(((-1 *b) +sqrt(d))/(2*a));
			cout<<" and "<<(((-1 *b) - sqrt(d))/(2*a));
		}
		else
		{	
			cout<<"Complex Roots."<<endl;
			cout<<"Roots of equation: \n"<<
				(-1*b)/(2*a)<<" + i"<<sqrt(-1*d)<<endl;
		cout<<(-1*b)/(2*a)<<" - i"<<sqrt(-1*d)<<endl;
		}
		cout<<"If you want to continue then 
enter'y' or 'Y':"<<endl;
		cin>>choice;
	}while(choice =='y' || choice =='Y');
}

Output:

Quadratic equation form: ax^2 +bx+c = 0
 Enter a:2
 Enter b:4
 Enter c:2
Root of equation is: -2
If you want to continue then enter'y' or 'Y': n
0 0

Discussions

Post the discussion to improve the above solution.