user2797441
user2797441

Reputation: 1

Code for quadratic equation gives incorrect answer

Hello I'm a Beginner in C#. I have made this code for quadratic equation. It runs but does not give the right answer.

using System;
using System.Diagnostics;


namespace mynamespace
{
    class myclass
    {
        static void Main(string[] args)
        {
            float a, b, c, x1, x2;
            Console.Write("Enter Value in a");
                a=Convert.ToSingle(Console.ReadLine());
            Console.WriteLine("Enter Value in b");
                b=Convert.ToSingle(Console.ReadLine());
            Console.WriteLine("Enter Value in c");
                c=Convert.ToSingle(Console.ReadLine());

            x1=(-b + Math.Sqrt ( b*b - 4*a*c)/(2*a));
            x2=(-b - Math.Sqrt ( b*b - 4*a*c)/(2*a));
            Console.WriteLine(x1);
            Console.WriteLine(x2);
            Console.ReadKey();

                    }
    }
}

Upvotes: 0

Views: 1579

Answers (2)

Stanislav Bozhanov
Stanislav Bozhanov

Reputation: 41

You can't convert float to string. You do:

a = float.Parse(Console.Readline());

And you must do an if statement:

if((b*b - 4*a*c) < 0)
{
   Console.WriteLine("There are no real roots!");
}

And you put the rest of your code in an else statement.

Upvotes: 0

musical_coder
musical_coder

Reputation: 3896

You're missing a set of parentheses; change your code to:

x1=((-b + Math.Sqrt ( b*b - 4*a*c))/(2*a));
x2=((-b - Math.Sqrt ( b*b - 4*a*c))/(2*a));

Upvotes: 7

Related Questions