C# :: Aufgabe #249 :: Lösung #3
3 Lösungen

#249
Taschenrechner in einer Konsole
Fortgeschrittener - C#
von Gelöschte Person
- 30.03.2019 um 19:29 Uhr
Programmiere einen Taschenrechner der folgende Rechenarten kann:
Plus
Minus
Mal
Geteilt
Wurzel
Hoch
Prozent
Quersumme
Plus
Minus
Mal
Geteilt
Wurzel
Hoch
Prozent
Quersumme
#3

von JKooP (18090 Punkte)
- 02.04.2020 um 14:40 Uhr
NET Core 3.x
C#-Code
C#-Code
C#-Code

using static System.Console; namespace CS_Aufgabe_249_Taschenrechner { class Program { static void Main(string[] args) { PrintInfo(); Write("Bitte Operation eingeben: "); // 144° (Wurzel aus 144) var calc = new Calculator(ReadLine()); WriteLine(calc); // 144° = 12 } static void PrintInfo() { WriteLine("Mögliche Operationen:"); WriteLine("(+) Addition\n(-) Subtraktion\n(*) Multiplikation\n(/) Division"); WriteLine("(^) Hoch\n(°) Wurzel\n(%) Prozent\n(#) Quersumme"); WriteLine("(&) Bitweises UND (nur INT)\n"); WriteLine("Nur 2 Operanden und ein Operator möglich!\n"); WriteLine("Beispiele: 2+2; -2 - -3; 4^2; 27°3; 20,4 % 84,5; 2&2; 123456789#\n"); WriteLine("Leerzeichen zwischen Zahlen und Operatoren möglich!\n"); } } }

using System; using System.Text.RegularExpressions; using System.Linq; namespace CS_Aufgabe_249_Taschenrechner { class Calculator { private readonly string _mathProblem; public Calculator(string mathProblem) => _mathProblem = mathProblem; private double GetResult(char op, (double a, double b) v) { var (s, d, p, q) = MyMath.Operation(v.a, v.b); return op switch { '+' => s, '&' => (int)v.a & (int)v.b, '-' => d, '*' => p, '/' => q, '°' => Math.Pow(v.a, 1 / Math.Abs(v.b)), '^' => Math.Pow(v.a, v.b), '%' => v.b * v.a / 100, '#' => MyMath.DigitSum((int)v.a), _ => 0 }; } private char GetOperator() { var r = new Regex(@"[+°*^/%#&\-]{1}"); var m = r.Matches(_mathProblem).Cast<Match>().Select(x => x.Value[0]).ToArray(); return m.Length switch { 0 => '0', 1 => m[0], _ => m[0] == '^' ? m[0] : m[1] }; } private (double v1, double v2) GetValues() { var v1 = 0.0; var v2 = 2.0; var r = new Regex(@"[\-]?[0-9,]+").Matches(_mathProblem); if (r.Count > 0) _ = double.TryParse(r[0].ToString(), out v1); if (r.Count > 1) _ = double.TryParse(r[1].ToString(), out v2); return (v1, v2); } public override string ToString() => $"{_mathProblem} = {GetResult(GetOperator(), GetValues())}"; } }

namespace CS_Aufgabe_249_Taschenrechner { static class MyMath { public static (double s, double d, double p, double q) Operation(double a, double b) => (a + b, a - b, a * b, a / (b == 0 ? 1 : b)); public static int DigitSum(int n) => n != 0 ? n % 10 + DigitSum(n / 10) : 0; } }
Kommentare:
Für diese Lösung gibt es noch keinen Kommentar
Seite 1 von 0
1