Note: This website is archived. For up-to-date information about D projects and development, please visit wiki.dlang.org.

Quadratic Equation (getting input and doing calculations)

Part of TutorialFundamentals

Description

This program will calculate the real roots for a user-specified quadratic equation.

Example

```import std.stdio; /* for writef/writefln */
import std.math;  /* for sqrt */

/*
For the quadratic equation: ax^2 + bx + c = 0
Roots =  (-b +/- sqrt ( b^2 - 4ac )) / 2a

For example:
a = 1, b = -5, c = 6
The roots are 2 and 3.
*/

int main()
{
double a, b, c, d;

writeln("For the equation: ax^2 + bx + c = 0");

write("What is a? ");
scanf("%lf", &a);

writef("What is b? ");
scanf("%lf", &b);

writef("What is c? ");
scanf("%lf", &c);

writefln("\nFor a = %s, b = %s, c = %s:", a, b, c);

d = (b * b) - (4 * a * c);

if (d < 0)
{
writefln("There are no real roots.");
}
else
{
double r1, r2;

r1 = (-b - sqrt (d)) / (2 * a);
r2 = (-b + sqrt (d)) / (2 * a);

if(r1 == r2)
writefln("Root: %s", r1);
else
writefln("Roots: %s, %s", r1, r2);
}

return 0;
}
```