How to pass a hard coded differential equation through Runge-Kutta 4 - c#

I'm trying to implement Runge-Kutta for example problems
dy/dt = y - t^2 + 1 and dy/dt = t * y + t^3 in C# and I cannot seem to get the output I'm expecting. I have split my program into several classes to try and look at the work individually. I think that my main error is coming from trying to pass a method through the Runge-Kutta process as a variable using a delegate.
Equation Class:
namespace RK4
{
public class Eqn
{
double t;
double y;
double dt;
double b;
public Eqn(double t, double y, double dt, double b)
{
this.t = t;
this.y = y;
this.dt = dt;
this.b = b;
}
public void Run1()
{
double temp;
int step = 1;
RK4 n = new RK4();
while (t < b)
{
temp = n.Runge(t, y, dt, FN1);
y = temp;
Console.WriteLine("At step number {0}, t: {1}, y: {2}", step, t, y);
t = t + dt;
step++;
}
}
public void Run2()
{
int step = 1;
RK4 m = new RK4();
while (t < b)
{
y = m.Runge(t, y, dt, FN2);
Console.WriteLine("At step number {0}, t: {1}, y: {2}", step, t, y);
t = t + dt;
step++;
}
}
public static double FN1(double t, double y)
{
double x = y - Math.Pow(t, 2) + 1;
return x;
}
public static double FN2(double t, double y)
{
double x = t * y + Math.Pow(t, 3);
return x;
}
}
}
Then Runge-Kutta 4 Class:
namespace RK4
{
class RK4
{
public delegate double Calc(double t, double y);
public double Runge(double t, double y, double dt, Calc yp)
{
double k1 = dt * yp(t, y);
double k2 = dt * yp(t + 0.5 * dt, y + k1 * 0.5 * dt);
double k3 = dt * yp(t + 0.5 * dt, y + k2 * 0.5 * dt);
double k4 = dt * yp(t + dt, y + k3 * dt);
return (y + (1 / 6) * (k1 + 2 * k2 + 2 * k3 + k4));
}
}
}
And my Program Class:
namespace RK4
{
class Program
{
static void Main(string[] args)
{
RunProgram();
}
public static void RunProgram()
{
Console.WriteLine("*******************************************************************************");
Console.WriteLine("************************** Fourth Order Runge-Kutta ***************************");
Console.WriteLine("*******************************************************************************");
Console.WriteLine("\nWould you like to implement the fourth-order Runge-Kutta on:");
string Fn1 = "y' = y - t^2 + 1";
string Fn2 = "y' = t * y + t^3";
Console.WriteLine("1) {0}", Fn1);
Console.WriteLine("2) {0}", Fn2);
Console.WriteLine("Please enter 1 or 2");
switch (Int32.Parse(Console.ReadLine()))
{
case 1:
Console.WriteLine("\nPlease enter beginning of the interval (a):");
double a = Double.Parse(Console.ReadLine());
Console.WriteLine("Please enter end of the interval (b):");
double b = Double.Parse(Console.ReadLine());
Console.WriteLine("Please enter the step size (h) to be used:");
double h = Double.Parse(Console.ReadLine());
Console.WriteLine("Please enter the inital conditions to satisfy y({0}) = d",a);
Console.WriteLine("d = ");
double d = Double.Parse(Console.ReadLine());
Console.Clear();
Console.WriteLine("Using the interval [{0},{1}] and step size of {2} and the inital condition of y({3}) = {4}:", a, b, h, a, d);
Console.WriteLine("With equation: {0}", Fn1);
Eqn One = new Eqn(a, d, h, b);
One.Run1();
Console.WriteLine("Press enter to exit.");
Console.ReadLine();
Environment.Exit(1);
break;
case 2:
Console.WriteLine("\nPlease enter beginning of the interval (a):");
a = Double.Parse(Console.ReadLine());
Console.WriteLine("Please enter end of the interval (b):");
b = Double.Parse(Console.ReadLine());
Console.WriteLine("Please enter the step size (h) to be used:");
h = Double.Parse(Console.ReadLine());
Console.WriteLine("Please enter the inital conditions to satisfy y({0}) = d",a);
Console.WriteLine("d = ");
d = Double.Parse(Console.ReadLine());
Console.Clear();
Console.WriteLine("Using the interval [{0},{1}] and step size of {2} and the inital condition of y({3}) = {4}:", a, b, h, a, d);
Console.WriteLine("With equation: {0}", Fn1);
Eqn Two = new Eqn(a, d, h, b);
Two.Run2();
Console.WriteLine("Press enter to exit.");
Console.ReadLine();
Environment.Exit(1);
break;
default:
Console.WriteLine("Improper input, please press enter to exit.");
Console.ReadLine();
Environment.Exit(1);
break;
}
}
}
}
This is not elegant programming by any means but I don't have the working knowledge to know what I'm doing wrong at this point. From what I was reading I thought that the delegate within the RK4 class would be able to pass through my hard coded diff eq.

You are doing a classical error in the RK4 implementation: Having two variants to position the multiplication with dt to choose from, you are using both.
It is either
k2 = dt*f(t+0.5*dt, y+0.5*k1)
or
k2 = f(t+0.5*dt, y+0.5*dt*k1)
and analogously in the other lines of the algorithm.

Related

Why does it say that there's a casting error

I am pretty new to C# and I'm stuck with a problem in the code. Apparently, there is a casting error, can you tell me what is it?
Here's the code
public static void Main(string[] args)
{
// side a and b
Console.WriteLine("Side A of 90° triangle");
double a = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Side B");
double b = Convert.ToDouble(Console.ReadLine());
// c^2
int csqr = (a * a) + (b * b);
int hypo = Math.Sqrt(csqr);
// hypo
Console.WriteLine("hypotenuse:- " + hypo);
}
The variables csqr and hypo should be of type double while you defined them as int.
Sqrt is a method to find the square root. thus it takes a parameter of type double and returns double.
sqrt documentation
csqr variable should be of type double because of the arithmetic operations on a double operands.
You cannot put a double into an int. Variables hypo csqr must be double.
public static void Main(string[] args)
{
//side a and b
Console.WriteLine("Side A of 90° triangle");
double a = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Side B");
double b = Convert.ToDouble(Console.ReadLine());
//c^2
double csqr = (a * a) + (b * b);
double hypo = Math.Sqrt(csqr);
//hypo
Console.WriteLine("hypotenuse:- " + hypo);
}

Simple C# mortgage formula calculating wrong

Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MortgageApplication
{
class Program
{
static void Main(string[] args)
{
string input = "", year, principle, month;
double r, y, p;
bool valid = false;
y = 0;
r = 0;
p = 0;
while (valid == false)
{
Console.WriteLine("Enter the duration of the loan (Number of Years): ");
input = Console.ReadLine();
if (double.TryParse(input, out y))
{
Console.WriteLine(y);
valid = true;
}
}
valid = false;
while (valid == false)
{
Console.WriteLine("Enter the princple ammount: ");
input = Console.ReadLine();
if (double.TryParse(input, out p))
{
Console.WriteLine(p);
valid = true;
}
}
valid = false;
while (valid == false)
{
Console.WriteLine("Enter the Interest Rate ");
input = Console.ReadLine();
if (double.TryParse(input, out r))
{
valid = true;
}
}
r = r / 100;
Console.WriteLine(r);
double top = p * r / 1200;
Console.WriteLine(top);
double x = (1 + (r / 1200.0));
Console.WriteLine(x);
double n = -12 * y;
Console.WriteLine(n);
double buttom = (1 - (Math.Pow(x, n)) );
Console.WriteLine(buttom);
double solution = top / buttom;
Console.WriteLine(solution);
Console.ReadLine();
}
}
}
This is suppose to be a simple mortgage app. I have the functionality but the formula is not correct.
Not sure if it's because I'm using doubles or if the problem is with my coding.
(p r / 1200.0) / (1 - (1.0 + r / 1200.0) ^(-12.0 n)),
Where
p = principal (dollars)
n = number of years
r = interest rate (percent)
m = monthly payment
So I think the direct answer is that you're dividing the rate by 100, then dividing it again by 1200. You should either not divide by 100 to start with, or only divide by 12 later (I like the second option because it makes it clear you're talking about 12 months).
Another thing you might consider, in order to reduce repeated code, is to factor out a new function that gets a double from the user. Something like:
private static double GetDoubleFromUser(string prompt)
{
double result;
while (true)
{
if (prompt != null) Console.Write(prompt);
var input = Console.ReadLine();
if (double.TryParse(input, out result)) break;
Console.WriteLine("Sorry, that is not a valid number. Please try again...");
}
return result;
}
Now, when you need a double, you just call this function and pass the prompt string. This makes your code much cleaner and easier to read. For example, your code could now be written as:
private static void Main()
{
double years = GetDoubleFromUser("Enter the duration of the loan (in years): ");
double principal = GetDoubleFromUser("Enter the princple ammount: ");
double rate = GetDoubleFromUser("Enter the interest rate: ") / 100;
Console.WriteLine("\nBased on these values entered:");
Console.WriteLine(" - Number of years .... {0}", years);
Console.WriteLine(" - Principal amount ... {0:c}", principal);
Console.WriteLine(" - Interest rate ...... {0:p}", rate);
double monthlyRate = rate / 12;
double payments = 12 * years;
double result =
principal *
(monthlyRate * Math.Pow(1 + monthlyRate, payments)) /
(Math.Pow(1 + monthlyRate, payments) - 1);
Console.WriteLine("\nYour monthly payment will be: {0:c}", result);
Console.ReadLine();
}

Quadratic Equation Solver in C#

I'm trying to write a simple quadratic equation solver in C#, but for some reason it's not quite giving me the correct answers. In fact, it's giving me extremely large numbers as answers, usually well into the millions.
Could anyone please shed some light? I get the exact same answer for the positive root and the negative root as well. (Tried two different methods of math)
static void Main(string[] args)
{
int a;
int b;
int c;
Console.WriteLine("Hi, this is a Quadratic Equation Solver!");
Console.WriteLine("a-value: ");
try
{
a = int.Parse(Console.ReadLine());
Console.WriteLine("b-value: ");
b = int.Parse(Console.ReadLine());
Console.WriteLine("c-value: ");
c = int.Parse(Console.ReadLine());
Console.WriteLine("Okay, so your positive root is: " + quadForm(a, b, c, true));
Console.WriteLine("And your negative root is: " + quadForm(a, b, c, false));
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.ReadLine();
}
static int quadForm(int a, int b, int c, Boolean pos)
{
int x = 0;
if (pos)
x = ((-b + (int) (Math.Sqrt((b * b) - (4 * a * c)))) / (2 * a));
else
x = ((-Math.Abs(b) - (int) (Math.Sqrt(Math.Pow(b,2) - (4 * a * c)))) / (2 * a));
return x;
}
Try this version of quadForm:
static double quadForm(int a, int b, int c, bool pos)
{
var preRoot = b * b - 4 * a * c;
if (preRoot < 0)
{
return double.NaN;
}
else
{
var sgn = pos ? 1.0 : -1.0;
return (sgn * Math.Sqrt(preRoot) - b) / (2.0 * a);
}
}

C# console application calculation loops

Hi it is just a simple calculator. I want to allow user to enter "N" or "n" after I asked them if they want to make an another conversion.
(Enter Y to make an another conversion/Enter N return to Main menu). How do I do that?
static int LengthCalculator() {
int LengthCalculatorOption;
string AnotherConversion = null;
double Centimetres = 0.0, Feet = 0.0, Inches = 0.0, TotalInches = 0.0;
const double CENTIMETRES_PER_INCH = 2.54, INCHES_PER_FOOT = 12;
do {
LengthCalculatorMenu();
LengthCalculatorOption = ValidLengthCalculatorReadOption();
if (LengthCalculatorOption == 1) {
Console.WriteLine("Please Enter the Centimetres(cm) that you wish to convert to feet and inches:");
Centimetres = double.Parse(Console.ReadLine());
TotalInches = (Centimetres / CENTIMETRES_PER_INCH); // This will take a floor function of Centimetres/2.54
Feet = (TotalInches - TotalInches % INCHES_PER_FOOT) / INCHES_PER_FOOT; // This will make it divisible by 12
Inches = TotalInches % INCHES_PER_FOOT; // This will give you the remainder after you divide by 12
Console.WriteLine("\nThe equivalent in feet and inches is {0} ft {1} ins", Feet, Inches);
Console.Write("\nWould you like to make an another conversion? \n\n(Enter Y to make an another conversion/Enter any key return to Main menu):");
AnotherConversion = Console.ReadLine();
} else if (LengthCalculatorOption == 2) {
Console.WriteLine("Please Enter the Feet:");
Feet = double.Parse(Console.ReadLine());
Console.WriteLine("Please Enter the Inches:");
Inches = double.Parse(Console.ReadLine());
Centimetres = ((Feet * INCHES_PER_FOOT) + Inches) * CENTIMETRES_PER_INCH;
Console.WriteLine("\nThe equivalent in centimetres is {0}cm", Centimetres);
Console.Write("\nWould you like to make an another conversion? \n\n(Enter Y to make an another conversion/Enter any key return to Main menu):");
AnotherConversion = Console.ReadLine();
}
} while (AnotherConversion == "y" || AnotherConversion == "Y");
return LengthCalculatorOption;
}//End LenthCalculator
static void LengthCalculatorMenu() {
string LengthCalculatorMenu = ("Enter 1) Convert Centimetres to Feet and Inches:"
+ "\nEnter 2) Convert feet and inches to centimetres:");
Console.WriteLine(LengthCalculatorMenu);
} // End LengthCalculatorMenu
static int ValidLengthCalculatorReadOption() {
int LengthCalculatorOption;
bool ValidLengthCalculatorOption = false;
do {
LengthCalculatorOption = int.Parse(Console.ReadLine());
if ((LengthCalculatorOption >= 1) && (LengthCalculatorOption <= 2)) {
ValidLengthCalculatorOption = true;
} else {
ValidLengthCalculatorOption = false;
} // end if
if (!ValidLengthCalculatorOption) {
Console.WriteLine("\n\t Option must be 1 or 2, Please Re-Enter your Option");
LengthCalculatorMenu();
} //end if
} while (!ValidLengthCalculatorOption);
return LengthCalculatorOption;
}// End LengthCalculatorReadOption
static int ReadMainMenuOption() {
int option = 0;
bool ValidMainMenuOption = false;
do {
option = int.Parse(Console.ReadLine());
if ((option >= 1) && (option <= 5)) {
ValidMainMenuOption = true;
} else {
ValidMainMenuOption = false;
} // end if
if (option == 1) {
LengthCalculator();
} else if (option == 2) {
} else if (option == 3) {
} else if (option == 4) {
} else if (option == 5) {
} // end if
if (!ValidMainMenuOption) {
Console.WriteLine("\n\t\a Option must be 1,2,3,4 or 5");
DisplayMenu();
} //end if
} while (!ValidMainMenuOption);
return option;
} //end ReadOption
/* Displays Main Menu
* Precondition:true
* postcondition: DisplayMenu displayed
*/
static void DisplayMenu() {
string mainMenu = "\n1)Length Calculator"
+ "\n2)Body Mass Index Calculator"
+ "\n3)Waist to Height Calculator"
+ "\n4)Fuel Consumption Calculator"
+ "\n5)Exit the Calculator"
+ "\n\nEnter your option(1,2,3,4 or 5 to exit):";
Console.Write(mainMenu);
} //end DisplayMenu
static void Main(string[] args) {
const int Exit = 5;
int menuOption;
do {
DisplayMenu();
menuOption = ReadMainMenuOption();
} while (menuOption != Exit);
Console.Write("Thank you for using this Calculator. Press any Key to Exit");
//terminating message
Console.ReadKey();
}//end Main
You can make a separate method that will handle user input. For example, this method will determine if the user has entered a Y or N. If they haven't it re-prompt them to do so:
static bool AnotherConversion()
{
var prompt = "\nWould you like to make an another conversion? \n\n(Enter (Y) to make another conversion or (N) to return to the Main Menu):";
Console.WriteLine(prompt);
while (true)
{
var userInput = Console.ReadLine();
if (String.Compare("Y", userInput, StringComparison.Ordinal)
{
return true;
}
else if (String.Compare("N", userInput, StringComparison.Ordinal)
{
return false;
}
else
{
// Invlalid input, re-prompt
Console.WriteLine("Invalid Input, please enter or (Y) or (N)!");
Console.WriteLine(prompt);
}
}
}
You can them simply update your do/while loop so that the condition is based on the AnotherConversion method. This will allow the prompt to be asked whenever a calculation is done:
static int LengthCalculator() {
....
do {
.....
} while (AnotherConversion());
return LengthCalculatorOption;
}//End LenthCalculator
Call to this method in the place you want:
static bool shouldMakeAnotherConversion()
{
repeatQuestion:
// This shows the question to the user
Console.Write("Do you want to make another conversion (Y/N)? ");
ConsoleKeyInfo answer = Console.ReadKey(true);
switch (answer.Key)
{
case ConsoleKey.Y: return true;
case ConsoleKey.N: return false;
}
//If the user types any other key, the program will repeat the question
Console.WriteLine();
goto repeatQuestion;
}
class Program
{
public static void parameter(int num1, int num2, out int add, out int sub, out int mul, out float div)
{
add = num1 + num2;
sub = num1 - num2;
mul = num1 * num2;
div = (float)num1 / num2;
}
static void Main(string[] args)
{
int num1, num2;
int add, sub, mul;
float div;
Console.Write("Enter 1st number\t");
num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("\nEnter 2nd number\t");
num2 = Convert.ToInt32(Console.ReadLine());
Program.parameter(num1, num2, out add, out sub, out mul, out div);
Console.WriteLine("\n\n{0} + {1} = {2}", num1, num2, add);
Console.WriteLine("{0} - {1} = {2}", num1, num2, sub);
Console.WriteLine("{0} * {1} = {2}", num1, num2, mul);
Console.WriteLine("{0} / {1} = {2}", num1, num2, div);
Console.ReadLine();
}
}
}
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Type you first number :");
Console.WriteLine("Type you second number :");
Console.WriteLine("Enter the operation + (addition), - (soustraction), * (multiplication), / (division)");
string stringOperation = Console.ReadLine();
switch (operation)
{
case 1:
result = firstNumber + secondNumber;
break;
case 2:
result = firstNumber - secondNumber;
break;
case 3:
result = firstNumber * secondNumber;
break;
case 4:
result = firstNumber / secondNumber;
break;
}
}
}
}

Quadratic equation formula

I am trying to make a program that calculates the answer of a quadratic equation with the general formula but i am encountering a few errors.
The way I have my Windows Form Application set up it asks for a, b, and c, and substitutes them in the general formula.
I have 3 text boxes, one for each value of a, b and c and one more for the answer, and it is supposed to work with a button I called "calculate".
My problem is that when I try something other than a perfect trinomial square, the answer comes up as NaN.
Here is some of the code I have:
private void textBox1_TextChanged(object sender, EventArgs e)
{
a = Double.Parse(textBox1.Text);
}
^ This is how I am assigning values to the variables
double sqrtpart = b * b - 4 * a * c;
answer = (b + Math.Sqrt(sqrtpart)) / 2 * a;
textBox4.Text = answer.ToString();
group 2a and make sure values are valid (b^2 > 4ac)
answer = (b + Math.Sqrt(sqrtpart)) / (2 * a);
First, make sure that 4ac < b². The quadratic formula also utilizes the ± sign, so we must make two separate variables to hold the two different answers.
double sqrtpart = (b * b) - (4 * a * c);
answer1 = ((-1)*b + Math.Sqrt(sqrtpart)) / (2 * a);
answer2 = ((-1)*b - Math.Sqrt(sqrtpart)) / (2 * a);
textBox4.Text = answer1.ToString() + " and " + answer2.ToString();
If you want your calculator to be able to compute complex numbers try the following
string ans = "";
double root1 = 0;
double root2 = 0;
double b = 0;
double a = 0;
double c = 0;
double identifier = 0;
a =Convert.ToDouble(Console.ReadLine());
b = Convert.ToDouble(Console.ReadLine());
c = Convert.ToDouble(Console.ReadLine());
identifier = b * b - (4 * a * c);
if (identifier > 0)
{
root1 = (-b+(Math.Sqrt(identifier)/(2*a)));
root2 = (-b - (Math.Sqrt(identifier) / (2 * a)));
string r1 = Convert.ToString(root1);
string r2 = Convert.ToString(root2);
ans = "Root1 =" + r1 + "Root2 = " + r2;
Console.WriteLine(ans);
}
if (identifier < 0)
{
double Real = (-b / (2 * a));
double Complex = ((Math.Sqrt((identifier*(-1.00))) / (2 * a)));
string SReal = Convert.ToString(Real);
string SComplex = Convert.ToString(Complex);
ans = "Roots = " + SReal + "+/-" + SComplex + "i";
Console.WriteLine(ans);
}
if (identifier == 0)
{
root1 = (-b / (2 * a));
string Root = Convert.ToString(root1);
ans = "Repeated roots : " + Root;
}
Use the following code:
using System;
using System.Collections.Generic;
using System.Text;
namespace SoftwareAndFinance
{
class Math
{
// quadratic equation is a second order of polynomial equation in a single variable
// x = [ -b +/- sqrt(b^2 - 4ac) ] / 2a
public static void SolveQuadratic(double a, double b, double c)
{
double sqrtpart = b * b - 4 * a * c;
double x, x1, x2, img;
if (sqrtpart > 0)
{
x1 = (-b + System.Math.Sqrt(sqrtpart)) / (2 * a);
x2 = (-b - System.Math.Sqrt(sqrtpart)) / (2 * a);
Console.WriteLine("Two Real Solutions: {0,8:f4} or {1,8:f4}", x1, x2);
}
else if (sqrtpart < 0)
{
sqrtpart = -sqrtpart;
x = -b / (2 * a);
img = System.Math.Sqrt(sqrtpart) / (2 * a);
Console.WriteLine("Two Imaginary Solutions: {0,8:f4} + {1,8:f4} i or {2,8:f4} + {3,8:f4} i", x, img, x, img);
}
else
{
x = (-b + System.Math.Sqrt(sqrtpart)) / (2 * a);
Console.WriteLine("One Real Solution: {0,8:f4}", x);
}
}
static void Main(string[] args)
{
// 6x^2 + 11x - 35 = 0
SolveQuadratic(6, 11, -35);
// 5x^2 + 6x + 1 = 0
SolveQuadratic(5, 6, 1);
// 2x^2 + 4x + 2 = 0
SolveQuadratic(2, 4, 2);
// 5x^2 + 2x + 1 = 0
SolveQuadratic(5, 2, 1);
}
}
}
Here is the original source.
A little late, but here is my solution:
using System;
using System.Collections.Generic;
namespace MyFunctions
{
class Program
{
static void Main(string[] args)
{
printABCSolution(1, -3, 4);
printABCSolution(1, -4, 4);
printABCSolution(1, -5, 4);
printABCSolution(9, 30, 25);
printABCSolution(9, -15, 25);
Console.ReadKey();
}
private static void printABCSolution(double a, double b, double c)
{
Console.WriteLine($"Solution a={a} b={b} c={c}");
var solution = ABCMath.ABCFormula(a, b, c);
Console.WriteLine($"# Solutions found: {solution.Count}");
solution.ForEach(x => Console.WriteLine($"x={x}"));
}
}
public static class ABCMath
{
public static List<double> ABCFormula(double a, double b, double c)
{
// Local formula
double formula(int plusOrMinus, double d) => (-b + (plusOrMinus * Math.Sqrt(d))) / (2 * a);
double discriminant = b * b - 4 * a * c;
List<double> result = new List<double>();
if (discriminant >= 0)
{
result.Add(formula(1, discriminant));
if (discriminant > 0)
result.Add(formula(-1, discriminant));
}
return result;
}
}
}
Output:
Solution a=1 b=-3 c=4
# Solutions found: 0
Solution a=1 b=-4 c=4
# Solutions found: 1
x=2
Solution a=1 b=-5 c=4
# Solutions found: 2
x=4
x=1
Solution a=9 b=30 c=25
# Solutions found: 1
x=-1,66666666666667
Solution a=9 b=-15 c=25
# Solutions found: 0
Here is code:
using System;
namespace RoomPaintCost
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("This program applies quadratic formula to Ax^2+Bx+C=0 problems");
double[] ABC= getABC();
double[] answerArray=QuadFormula(ABC);
Console.WriteLine("Positive answer: {0:0.000} \n Negative answer: {1:0.000}", answerArray[0], answerArray[1]);
}
//Form of Ax^2 + Bx + C
//Takes array of double containing A,B,C
//Returns array of positive and negative result
public static double[] QuadFormula(double[] abc)
{
NotFiniteNumberException e = new NotFiniteNumberException();
try
{
double a = abc[0];
double b = abc[1];
double c = abc[2];
double discriminant = ((b * b) - (4 * a * c));
if (discriminant < 0.00)
{
throw e;
}
discriminant = (Math.Sqrt(discriminant));
Console.WriteLine("discriminant: {0}",discriminant);
double posAnswer = ((-b + discriminant) / (2 * a));
double negAnswer = ((-b - discriminant) / (2 * a));
double[] xArray= { posAnswer,negAnswer};
return xArray;
}
catch (NotFiniteNumberException)
{
Console.WriteLine("Both answers will be imaginary numbers");
double[] xArray = { Math.Sqrt(-1), Math.Sqrt(-1) };
return xArray;
}
}
public static double[] getABC()
{
Console.Write("A=");
string sA = Console.ReadLine();
Console.Write("B=");
string sB = Console.ReadLine();
Console.Write("C=");
string sC = Console.ReadLine();
int intA = Int32.Parse(sA);
int intB = Int32.Parse(sB);
int intC = Int32.Parse(sC);
double[] ABC = { intA, intB, intC };
return ABC;
}
}
}

Categories

Resources