Note: This website is archived. For up-to-date information about D projects and development, please visit wiki.dlang.org.
Version 3 (modified by jcc7, 17 years ago)
workaround for ampersand/semi-colon problem

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.c.stdio; /* for scanf */
import std.stdio; /* for writef/writefln */
import std.math; /* for sqrt */

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

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

  writef("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;
}
  /* 
    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.
  */

More Information

Note the use of curly braces around the bodies of the if and else clauses. These are compound statements and allow multiple statements to be executed as part of conditional and looping statements, such as if-else and while.