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

Changes from Version 1 of QuadraticEquationExample/D2

Show
Ignore:
Author:
Andrej08 (IP: 93.137.24.64)
Timestamp:
09/04/10 20:33:21 (14 years ago)
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • QuadraticEquationExample/D2

    v0 v1  
     1= Quadratic Equation (getting input and doing calculations) = 
     2 
     3''Part of'' TutorialFundamentals 
     4 
     5== Description == 
     6 
     7This program will calculate the real roots for a user-specified quadratic equation. 
     8 
     9== Example == 
     10 
     11{{{ 
     12#!d 
     13import std.stdio; /* for writef/writefln */ 
     14import std.math;  /* for sqrt */ 
     15 
     16/*  
     17    For the quadratic equation: ax^2 + bx + c = 0 
     18    Roots =  (-b +/- sqrt ( b^2 - 4ac )) / 2a 
     19 
     20    For example: 
     21    a = 1, b = -5, c = 6  
     22    The roots are 2 and 3. 
     23*/ 
     24 
     25int main()  
     26{ 
     27    double a, b, c, d; 
     28 
     29    writeln("For the equation: ax^2 + bx + c = 0"); 
     30 
     31    write("What is a? "); 
     32    scanf("%lf", &a); 
     33 
     34    writef("What is b? "); 
     35    scanf("%lf", &b); 
     36 
     37    writef("What is c? "); 
     38    scanf("%lf", &c); 
     39 
     40    writefln("\nFor a = %s, b = %s, c = %s:", a, b, c); 
     41 
     42    d = (b * b) - (4 * a * c); 
     43     
     44    if (d < 0)  
     45    { 
     46        writefln("There are no real roots."); 
     47    } 
     48    else  
     49    { 
     50        double r1, r2; 
     51 
     52        r1 = (-b - sqrt (d)) / (2 * a); 
     53        r2 = (-b + sqrt (d)) / (2 * a); 
     54 
     55        if(r1 == r2) 
     56            writefln("Root: %s", r1); 
     57        else 
     58            writefln("Roots: %s, %s", r1, r2); 
     59    } 
     60     
     61    return 0; 
     62} 
     63}}} 
     64 
     65== More Information == 
     66 
     67Note 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''.