Answer to Question #261113 in C# for Kiyemba Marvin

Question #261113
Suppose you want to find roots of a quadratic equation ax2+bx+c=0 where a, b and c are coefficients. 
This program will ask the coefficients: a, b and c from user and displays the roots.




1
Expert's answer
2021-11-04T08:37:49-0400
using System;

namespace Test
{
    class Roots
    {
        static double InputDouble(string title)
        {
            Console.Write(title);
            string tmp = Console.ReadLine();

            double result;
            if(!double.TryParse(tmp, out result))
            {
                throw new Exception("Bad input");
            }

            return result;
        }

        static int Main()
        {
            double a = InputDouble("Enter the coefficient a: ");
            double b = InputDouble("Enter the coefficient b: ");
            double c = InputDouble("Enter the coefficient c: ");

            double D = b*b - 4*a*c;

            if(D < 0)
            {
                Console.WriteLine("Result: no real roots");
            }
            else
            if(D == 0)
            {
                Console.WriteLine("Result: x = {0}", -b / (2*a));
            }
            else
            {
                double x1 = (-b + Math.Sqrt(D)) / (2*a);
                double x2 = (-b - Math.Sqrt(D)) / (2*a);
                Console.WriteLine("Result: x1 = {0}, x2 = {1}", x1, x2);
            }

            return 0;
        }
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS