C# :: Aufgabe #184 :: Lösung #3
4 Lösungen
#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
von daniel59 (4260 Punkte)
- 24.07.2017 um 12:02 Uhr
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
Seite 1 von 0
1
