Sunday, March 18, 2012

C Quadratic Equation Solver

Hello My Fellow Friends!

Today we are going to build a quadratic equation solver.

Why Quadratic Equation Solver?
-Good for home work, Saves you time and the energy!

Before we Start
Ok so I'm going to write this program in C, I'm using Bloodshed Dev- C/C++, which is based on GCC.
It doesn't matter what compiler you are using, but in my Project files, there is a .dev file that is meant for this compiler, in case you were wondering.

So Let's Start!
The quadratic equation solver will be mostly based on the....
Quadratic Equation
not very predictable.

The quadratic equation is:


(image from Wikipedia)



For an equation of the form:

(image from Wikipedia)



Now the equation can have three cases for any a,b,c, we determine the case by the Delta which is:

(guess what - image from Wikipedia)



case 1:
if Delta>0 (means it is positive) we have two different answers, x1 and x2.

case 2:
if Delta=0 we have one answer only, x.

case 3:
if Delta<0 (means it is negative) there is no answers (can't do square root of a negative number).

The program will use square root function, which is from the math library.
So we have to include the math.h as seen in the code.

That is the basic things that we need to know.
So here is my program


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

int main(int argc, char *argv[])
{
    int a,b,c; // aX^2 + bX + c = 0
    printf("Please Enter a,b,c\n");
    scanf("%d %d %d",&a,&b,&c);
    float d = b*b - (4*a*c);  //d = Delta
    
    if(d==0) printf("Delta = 0\n x=%f\n",(float)(-1*(b/2*a)));
    if(d<0) printf("Delta <0");
    else
    {
        if(d>0)
        {
              printf("Delta > 0\n x1=%f\n",(-1*b + sqrt(d))/2*a);
              printf("Delta > 0\n x2=%f\n",(-1*b - sqrt(d))/2*a);
        }
    }
  system("PAUSE"); 
  return 0;
}


Download This Project(rar file)

Notes:
- .c file is the code.
- .exe file is the output of this code (after compiling)
- .dev a file for Bloodshed Dev- C/C++ compiler.
-  Questions = Comments!

3 comments:

  1. Is there no void functions in C? <3

    ReplyDelete
    Replies
    1. There are "void" functions in C programming language.
      I used "int" function because it is the default type of the "Main" function int Dev C/C++.
      The early C programming language based on that every function has a return.
      The "void" type function was added to the language later.
      (:

      Delete
  2. What about dual number's solve? Do you have any idea?

    ReplyDelete