Skip to content

Instantly share code, notes, and snippets.

@d8ta
Created November 26, 2013 20:58
Show Gist options
  • Save d8ta/7666120 to your computer and use it in GitHub Desktop.
Save d8ta/7666120 to your computer and use it in GitHub Desktop.
using System;
using System.Linq;
namespace bsp30
{
/* 30. (2P)Schreibe 5 Funktionen, welche von einem eindimensionalen Fließkommazahlen-Array (Parameter der Funktion) beliebiger Größe
* Durchschnitt
* Summe
* Standardabweichung
* Minimum
* Maximum
*
* der Daten berechnen und zurückgeben. */
class MainClass
{
static double[] data;
// main
static void Main (string[] args)
{
data = new double[6]
{2, 4, 6, 8, 10, 12};
readInNumbersCommandLine();
Console.WriteLine("Summe: " + Summe());
Console.WriteLine("Durchschnitt: " + Durchschnitt());
Console.WriteLine("Maximum: " + Maximum());
Console.WriteLine("Minimum: " + Minimum());
Console.WriteLine("Standardabweichung: " + Standardabweichung());
} // end of main
// function to read in usernumbers
static int readInNumbersCommandLine()
{
Console.WriteLine("type in the width of your array:");
int input = secureDoubleInput();
return input;
} // end of function
// secure input
static int secureDoubleInput()
{
string stringInput;
int result;
bool success = true;
do
{
if (!success)
{
Console.WriteLine("your number is not valid, try again");
}
stringInput = Console.ReadLine();
success = int.TryParse(stringInput, out result);
}
while (!success);
return result;
} // end of function
// check user input for mistakes like negative numbers or strings
static double checkInput (double min, double max)
{
bool inputIsOK;
double userInput;
do {
inputIsOK = double.TryParse (Console.ReadLine (), out userInput);
if ((inputIsOK == true) && (userInput >= min) && (userInput <= max)) {
inputIsOK = true;
} else {
inputIsOK = false;
Console.WriteLine ("try again, your input is wrong!");
}
} while (inputIsOK == false);
return userInput;
} // end of function
// function for the sum
static double Summe()
{
double sum = 0;
for (int i = 0; i < data.Length; i++)
{
sum += data[i];
}
return sum;
} // end of function
// function for average
static double Durchschnitt ()
{
double average = Summe() / data.Length;
return average;
} // end of function
// function for max
static double Maximum()
{
double max = data.Max();
return max;
} // end of function
// function for min
static double Minimum()
{
double min = data.Min();
return min;
} // end of function
// function for standard deviation
static double Standardabweichung()
{
double average = Durchschnitt();
double sumOfSquares = data.Select(val => (val - average) * (val - average)).Sum();
double sd = Math.Sqrt(sumOfSquares / data.Length);
return sd;
} // end of function
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment