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();
}
Related
A user enters two prime numbers which are then multiplied together, and another calculation of (a-1) * (b-1) is completed (a and b being the prime numbers entered). a function to checks the numbers entered, if the numbers are NOT prime, the user will be asked to re-enter the numbers. However, when I test this, I've noticed that if the user inputs a number which ISN'T prime, and then re-enters a prime number, the calculations are based on the number which ISN'T prime. E.g. if the user enters 2 and 4, since 4 isn't prime they are asked to enter another number, e.g 3, the calculations will be based on the numbers 2 and 4.
How can I correct this so it takes the valid prime number and not the invalid number originally entered?
namespace example
{
class Program
{
class Co_P
{
static void coprime(ref int c, int calculation)
{
if (gcd(c, calculation) == 1)
Console.WriteLine("it's Co-Prime");
else
do
{
Console.WriteLine("it isn't Co-Prime");
Console.WriteLine("Enter a Co-Prime");
c = int.Parse(Console.ReadLine());
coprime(ref c, calculation);
} while (gcd(c, calculation) != 1);
}
static int Prime_a(int a) //check a is prime
{
if (a <= 1) return 0;
for (int i = 2; i <= a / 2; i++)
{
if (a % i == 0)
{
return 0; //not prime
}
}
return 1;
}
static void result(int a) //outputs if a is prime/or not
{
if (Prime_a(a) != 0)
{
Console.WriteLine(a + " is a prime number");
}
else do
{
Console.WriteLine(a + " isn't prime number");
Console.WriteLine();
Console.WriteLine("Please make sure you enter a prime number");
a = int.Parse(Console.ReadLine());
} while (Prime_a(a) == 0);
}
static int Prime_b(int b)
{
if (b <= 1) return 0;
for (int i = 2; i <= b / 2; i++)
{
if (b % i == 0)
{
return 0;
}
}
return 1;
}
static void resultb(int b)
{
int result = Prime_b(b);
if (Prime_b(b) != 0)
{
Console.WriteLine(b + " is a prime number");
}
else do
{
Console.WriteLine(b + " is not a prime number");
Console.WriteLine("Please make sure you enter a prime number");
b = int.Parse(Console.ReadLine());
} while (Prime_b(b) == 0);
}
static void Main(string[] args)
{
int a;
Console.WriteLine("Enter a prime number for a");
a = int.Parse(Console.ReadLine());
Console.WriteLine();
result(a);
Console.WriteLine();
int b;
Console.WriteLine("Enter a prime number for b");
b = int.Parse(Console.ReadLine());
Console.WriteLine();
resultb(b);
Console.WriteLine();
int total = a * b;
Console.WriteLine("The total of the prime numbers is = " + total);
int calculation = (a - 1) * (b - 1); //calculation
Console.WriteLine();
Console.WriteLine("The result = " + calculation);
Console.WriteLine();
}
}
}
You should extend result and resultb function so it returns new prompted valid number
static int result(int a) {
var result = Prime_a(a);
if (result != 0)
...code...
return result
}
Also don't forget to reassign those values
...code...
a = result(a);
...code...
b = resultb(b);
int b;
Console.WriteLine("Enter a prime number for b");
b = int.Parse(Console.ReadLine());
Console.WriteLine();
resultb(b);
Console.WriteLine();
In line resultb(b); you are passing int to method resultb. int is a value type, or in other words, passing int to a method means passing its value to a method, where copy of that value is created. In this case a copy of b is created in method resultb. Every further change on b inside method resultb is made on copy and original stays the same.
In resultb method pass parameter by reference by adding ref keyword. Instead
static void resultb(int b)
{
// code
}
method will look like this
static void resultb(ref int b)
{
// code
}
You will call the method this way
resultb(ref b);
Here's the portion of code.
int b;
Console.WriteLine("Enter a prime number for b");
b = int.Parse(Console.ReadLine());
Console.WriteLine();
resultb(ref b);
Console.WriteLine();
Now every change on passed b inside method resultb will reflect on the original.
You should do the same for method result(int a).
I started doing c# and now I'm having some issues. This is an assignment for the class I am taking. First I created a program that worked, but then I realised I missed out on the whole method thing. So I'm trying to redo the stuff. So basically I'm doing a program that converts fahrenheit to celsius, based on what the user types. So far I have this:
static double FahrenheittoCelsius(double fahr, double cel)
{
fahr = (cel * 9) / 5 + 32;
return fahr;
}
static void Main(string[] args)
{
double cel = 0;
double fahr = 97;
double max_temp = 170.6;
double min_temp = 163.4;
Console.WriteLine("Welcome to the sauna! We will find the optimal temperature for you! ");
do
{
Console.Write("Please type in Fahrenheit: ");
try
{
fahr = double.Parse(Console.ReadLine());
}
catch
{
Console.Write("Only numbers please!");
continue;
}
if (fahr >= max_temp)
{
Console.Write("The temperature you typed is {0} Celsius, type a lower temperature!", Math.Round(cel, 1));
}
else if (fahr <= min_temp)
{
Console.Write("Temperature you typed is {0} Celsius, type a higher temperature!", Math.Round(cel, 1));
}
else if (fahr > min_temp && fahr < max_temp)
{
Console.Write("Now the temperature is {0} celsius and now the temperature is optimal!", Math.Round(cel, 1));
}
} while (fahr > min_temp != fahr < max_temp);
Console.ReadLine();
So excuse my halfass translate since it was all in Swedish.
But my problem is I can't get the equation "fahr = (cel * 9) / 5 + 32 return fahr;" to my try and catch, which worked in my other program (where I didn't use the method). I can't get it to work.
All help is appreciated
Welcome to programming! You have several small issues with your code:
First looking at your method:
static double FahrenheittoCelsius(double fahr, double cel)
{
fahr = (cel * 9) / 5 + 32;
return fahr;
}
The method name should be FahrenheitToCelsius -- each word starting
with a capital letter.
According to the title of the method you are converting fahrenheit to
celsius. based on that you would only need to pass a fehrenheit and
return a celsius. You are passing both but then returning
fehrenheit!?
The formula you have is also wrong. It should be (F − 32) × 5/9 so code-wise:
var cel = (fahr - 32) * 5 / 9;
return cel;
Then in your main you need to call this method
cel = FahrenheitToCelsius(fahr);
static void Main(string[] args)
{
double cel = 0;
double fahr = 97;
double max_temp = 170.6;
double min_temp = 163.4;
Console.WriteLine("Welcome to the sauna! We will find the optimal temperature for you! ");
do
{
Console.Write("Please type in Fahrenheit: ");
try
{
fahr = double.Parse(Console.ReadLine());
cel = FahrenheitToCelsius(fahr);
}
catch
{
Console.Write("Only numbers please!");
continue;
}
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.
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;
}
}
}
}
I'm new to C#, well, coding in general.
I have done fairly well by myself to date, in this introduction course I am taking, but I ran into a road bump.
I am trying to figure out how to code a if statement that will run inside a loop to analyze 5 different ints as they are entered and to put the max int and min int seperatly so that I can ue the remaining three ints to make a calculation.
To be exact, validate user input and remove the min/max user input to average the remaining three.
PS, I tried an array but for some reason it wasn't working well. I don't have the code as I'm at work right now though. I was told in a lecture that an if statement should be used but arrays are possible too.
Thank you for your time and any possible answers.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string userIsFinished = "";
string name, city, value;
double rating, avg = 0;
double[] array1 = new double[5];
double max = 0;
double min = double.MaxValue;
double score, totalScore = 0;
//get basic information
do
{
Console.WriteLine("Please enter divers name.");
name = Console.ReadLine();
Console.WriteLine("Please enter the divers city.");
city = Console.ReadLine();
//get and validate user input for 1 dive rating
Console.WriteLine("Please enter a dive rating between 1.00 and 1.67.");
rating = Double.Parse(Console.ReadLine());
while (rating < 1 || rating > 1.69)
{
Console.WriteLine("Oops, you entered an invalid number. Please, enter a dive rating between 1.00 and 1.67.");
rating = Double.Parse(Console.ReadLine());
}
Console.ReadLine();
// get and validate user input for 5 judge scores
for (int s = 1; s <= 5; s++)
{
Console.WriteLine("Please enter the score for judge {0}.", s);
value = Console.ReadLine();
score = Convert.ToDouble(value);
while (score < 0 || score > 10)
{
Console.WriteLine("Invalid entry, please enter a number in between 0 - 10.");
score = Convert.ToDouble(Console.ReadLine());
}
array1[s] = Convert.ToDouble(score); //----this line keeps throwing an exception
}
Console.ReadLine();
//calculate totalScore by dropping min/max scores and averaging them times dive rating
foreach (int i in array1)
{
if (i > max)
max = i;
if (i < min)
min = i;
avg += i;
}
totalScore = avg * rating;
//Print gathered and calculated information
Console.WriteLine("Divers name: {0}", name);
Console.WriteLine("Divers city: {0}", city);
Console.WriteLine("Dive degree of difficulty: {0}", rating);
Console.WriteLine("Total dive score is: {0}", totalScore);
// Ask if user wants to process another diver and continue or exit program
Console.WriteLine("Would you like to enter another divers information? [Y]es [N]o: ");
userIsFinished = Console.ReadLine();
}
while
(userIsFinished.ToLower() != "n");
Console.ReadLine();
}
}
}
or you can go list route and
List<int> apples = new List<int>();
apples.Add(31);
apples.Add(34);
apples.Add(100);
apples.Add(57);
apples.Add(1);
int min = apples.Min();
int max = apples.Max();
apples.Remove(min);
apples.Remove(max);
decimal average = (decimal)(apples.Sum()) / apples.Count;
Not sure about your question... You want to know, the max and min about 5 values, and the avarage about the three others...
int[] n = { 4, 7, 29, 3, 87 };
int max = 0;
int min = int.MaxValue;
double avg = 0;
foreach (int i in n)
{
if (i > max)
max = i;
if (i < min)
min = i;
avg += i;
}
avg = avg / n.Count - 2;
try this code:
int[] a = new int[5];
int minpos;
int maxpos;
int min = Int32.MaxValue;
int max = a[0];
int temp = 0;
for (int i = 0; i < 5; i++)
{
Console.WriteLine(" Enter number " + (i + 1));
Int32.TryParse(Console.ReadLine(), out temp);
a[i] = temp;
//Decision Making Logic
if (min > temp)
{
min = temp;
minpos = i;
}
if (max < temp)
{
max = temp;
maxpos = i;
}
}
//At the end of this loop you will see that minpos contains the index of minimum element
//and maxpos contains index of maximum element,values in remaining indeces contain elements that are neither max or min in that //collection
Thanks guys, it appears I needed a good night of sleep. Thanks a ton for all these helpful answers as I'm sure I will be delving into those methods soon and it will be good to be able to get a head start on them. Here is my code,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string userIsFinished = "";
string name, city;
double rating, avg = 0;
double max = 0;
double min = 10;
double score, value = 0, totalScore = 0, finalScore = 0;
//get basic information
do
{
Console.WriteLine("\n");
Console.WriteLine("Please enter divers name.");
name = Console.ReadLine();
Console.WriteLine("Please enter the divers city.");
city = Console.ReadLine();
//get and validate user input for 1 dive rating
Console.WriteLine("Please enter a dive rating between 1.00 and 1.67.");
rating = Double.Parse(Console.ReadLine());
while (rating < 1 || rating > 1.69)
{
Console.WriteLine("Oops, you entered an invalid number. Please, enter a dive rating between 1.00 and 1.67.");
rating = Double.Parse(Console.ReadLine());
}
Console.ReadLine();
// get and validate user input for 5 judge scores
for (int s = 1; s <= 5; s++)
{
Console.WriteLine("Please enter the score for judge {0}.", s);
score = Convert.ToDouble(Console.ReadLine());
while (score < 0 || score > 10)
{
Console.WriteLine("Invalid entry, please enter a number in between 0 - 10.");
score = Convert.ToDouble(Console.ReadLine());
}
if (score > max)
max = score;
if (score < min)
min = score;
totalScore = score + totalScore;
}
Console.ReadLine();
\\Calculate values
value = totalScore - max - min;
avg = value / 3;
finalScore = avg * rating;
//Print gathered and calculated information
Console.WriteLine("Divers name: {0}", name);
Console.WriteLine("Divers city: {0}", city);
Console.WriteLine("Dive degree of difficulty: {0}", rating);
Console.WriteLine("Total dive score is: {0}", finalScore);
Console.WriteLine("\n");
// Ask if user wants to process another diver and continue or exit program
Console.WriteLine("Would you like to enter another divers information? [Y]es [N]o: ");
userIsFinished = Console.ReadLine();
}
while
(userIsFinished.ToLower() != "n");
Console.ReadLine();
Console.WriteLine("\n");
}
}
}