C# – Object Oriented Programming – Lab 1 (Roots of a quadratic equation)

So I thought I’d upload some of the C# Object Oriented Programming labs I was given in my Computer Games studies and my solutions for them. Here’s the first one:

Create a Windows Console application, with a number of variables:
a, b c (floats)
x1 and x2 (floats)
hasRoots (boolean)

The purpose of the program is to calculate the roots of the quadratic equation using the quadratic formula:

Here’s my solution for it:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace QuadraticEquation
class QuadraticEquation
static void Main(string[] args)
Console.Title = "The Console";
Console.WriteLine("Welcome to the console, time to solve a quadratic equation");

Console.Write("What is the value of a = ");
string aInput = Console.ReadLine();
float a = float.Parse(aInput);

Console.Write("What is the value of b = ");
string bInput = Console.ReadLine();
float b = float.Parse(bInput);

Console.Write("What is the value of c = ");
string cInput = Console.ReadLine();
float c = float.Parse(cInput);

float x1, x2;
bool hasRoots;

Console.WriteLine("a is " + a);
Console.WriteLine("b is " + b);
Console.WriteLine("c is " + c);

Console.WriteLine("Press any key to continue");

float squareRootPart;
squareRootPart = (b * b) - (4 * (a * c));
double squareRooted;
squareRooted = Math.Sqrt(squareRootPart);
float floatedSquareRoot = (float)squareRooted;
x1 = (-(b) + floatedSquareRoot) / (2 * a);
x2 = (-(b) - floatedSquareRoot) / (2 * a);

Console.WriteLine("So the quadratic equation has the roots.." + x1 + " and " + x2);

if (x1 == 0 && x2 == 0)
Console.WriteLine("The quadratic equation has no real roots");




Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s