C# :: Aufgabe #184 :: Lösung #3

4 Lösungen Lösungen öffentlich
#184

Wurzel ziehen mit Intervallschachtelung

Anfänger - C# von Felix - 11.07.2017 um 21:30 Uhr
Schreibe eine Methode die aus einer Zahl die Wurzel zieht, benutze dafür die Intervallschachtelung.
#3
vote_ok
von daniel59 (4260 Punkte) - 24.07.2017 um 12:02 Uhr
Quellcode ausblenden C#-Code
using System;

namespace ConsoleIntervallschachtelung
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("----- Wurzel ziehen mit Intervallschachtelung -----");
            Console.Write("Geben Sie eine positve Zahl ein: ");
            decimal d;
            if (decimal.TryParse(Console.ReadLine(), out d) && d >= 0)
            {
                Console.Write("Anzahl der Nachkommastellen (0-14): ");
                int decimals;
                if (int.TryParse(Console.ReadLine(), out decimals) && decimals >= 0 && decimals <= 14)
                {
                    decimal sqrt = Sqrt(d, decimals);
                    Console.WriteLine($"Die Wurzel von {d} ist ungefähr: {sqrt}");
                }
                else
                {
                    Console.WriteLine("Fehlerhafte Eingabe");
                }
            }
            else
            {
                Console.WriteLine("Fehlerhafte Eingabe");
            }
            Console.ReadLine();
        }

        static decimal Sqrt(decimal d, int decimals, int currentDecimals = 0, decimal start = 0)
        {
            if (d < 0)
            {
                return decimal.MinusOne;
            }

            decimal increment = (decimal)Math.Pow(10, -currentDecimals);
            for (decimal i = start; i < int.MaxValue; i += increment)
            {
                decimal a = Math.Round((decimal)Math.Pow((double)i, 2), currentDecimals * 2);
                decimal b = Math.Round((decimal)Math.Pow((double)(i + increment), 2), currentDecimals * 2);
                if (a == d)
                {
                    return i;
                }
                else if (b == d)
                {
                    return i + increment;
                }
                else if (a < d && d < b)
                {
                    if (currentDecimals >= decimals)
                    {
                        return Math.Round(i, decimals);
                    }
                    return Math.Round(Sqrt(d, decimals, currentDecimals + 1, i), decimals);
                }
            }

            return decimal.MinusOne;
        }
    }
}

Kommentare:

Für diese Lösung gibt es noch keinen Kommentar

Bitte melden Sie sich an um eine Kommentar zu schreiben.
Kommentar schreiben