Code Snippets

  

C++ Source Code


Welcome to Dream.In.Code
Become a C++ Expert!

Join 149,621 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 1,922 people online right now. Registration is fast and FREE... Join Now!





Quadratic Formula

This program computes all real and non-real (imaginary) roots/zeros for an equation using the quadratic formula.

Submitted By: SPlutard
Actions:
Rating:
Views: 8,736

Language: C++

Last Modified: March 20, 2006
Instructions: This is a complete program, but feel free to eliminate/add to it in order to make it into a function for another program, or whatever is needed to fit your needs. It will work perfectly fine on its own, as well.

Snippet


  1. // imaginary_Quad_Form.cpp : This program will compute all the roots/zeros of a quadratic equation (including imaginary ones).
  2. //
  3.  
  4. #include "stdafx.h"
  5. #include <iostream>
  6. #include <math.h>
  7.  
  8. main()
  9. {
  10.      float a, b, c, y1, y2, dis;
  11.  
  12.      std::cout<<"This program will compute the roots/zeros of a quadratic equation (including imaginary ones).\n\n"<<"Please enter a, b, and c from the form: y = aX^2 + bX + c\n"<<"a = ";
  13.      std::cin>>a;
  14.      std::cout<<"b = ";
  15.      std::cin>>b;
  16.      std::cout<<"c = ";
  17.      std::cin>>c;
  18.      dis = ((b*b)-(4*a*c));
  19.      if(((b*b)-(4*a*c))<0)
  20.      {
  21.           dis = -1 * dis;
  22.           y1 = ((-1 * b) + (sqrt(dis)))/(2 * a);
  23.           y2 = ((-1 * b) - (sqrt(dis)))/(2 * a);
  24.           if(y1 == y2) std::cout<<"\a\nThe root is: "<<y1<<"i\n\n\n";
  25.           else std::cout<<"\a\nThe roots are: "<<y1<<"i and "<<y2<<"i\n\n\n";
  26.      }
  27.      else
  28.      {
  29.           y1 = ((-1 * b) + (sqrt(dis)))/(2 * a);
  30.           y2 = ((-1 * b) - (sqrt(dis)))/(2 * a);
  31.           if(y1 == y2) std::cout<<"\a\nThe root is: "<<y1<<"\n\n\n";
  32.           else std::cout<<"\a\nThe roots are: "<<y1<<" and "<<y2<<"\n\n\n";
  33.      }
  34.  
  35.      system("Pause");
  36.      return 0;
  37. }

Copy & Paste


Comments


There are currently no comments for this snippet. Be the first to comment!

Add comment


You must be registered and logged on to </dream.in.code> to leave comments.




Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month