Advertisement
Guest User

Untitled

a guest
Oct 18th, 2019
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.19 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4.  
  5. namespace ConsoleApp2
  6. {
  7.     class Program
  8.     {
  9.         static void Main(string[] args)
  10.         {
  11.             string shit = "2.6*x^2 + (-0.9)*x + (-3.5)";
  12.             Console.WriteLine(Parser(shit));
  13.         }
  14.  
  15.         public static bool IsZero(double number)
  16.         {
  17.             return System.Math.Abs(number) <= 10e-6;
  18.         }
  19.         public static string SolvePolynom(double first, double second, double third)
  20.         {
  21.             if (IsZero(first))
  22.             {
  23.                 if (IsZero(second))
  24.                 {
  25.                     if (IsZero(third))
  26.                         return "1";
  27.                     return "no roots";
  28.                 }
  29.                 else
  30.                 {
  31.                     return third / second + "";
  32.                 }
  33.             }
  34.             else
  35.             {
  36.                 var discriminant = second * second - 4 * first * third;
  37.                 if (discriminant < 0)
  38.                 {
  39.                     return "no roots";
  40.                 }
  41.                 else
  42.                 {
  43.                     return (System.Math.Sqrt(discriminant) - second) / (2 * first) + "";
  44.                 }
  45.             }      
  46.         }
  47.         static string Parser(string text)
  48.         {
  49.             var coefs = new List<double>();
  50.             var shit = text.Split('+');
  51.            
  52.             foreach (var s in shit)
  53.             {
  54.  
  55.                 var number = new StringBuilder();
  56.                 for (int i = 0; i < s.Length; i++)
  57.                 {
  58.                     if (char.IsLetter(s[i])) break;
  59.  
  60.                     if (char.IsDigit(s[i]) || s[i] == '.' || s[i] == '-')
  61.                     {
  62.                         number.Append(s[i]);
  63.                     }
  64.                 }
  65.                 var numberStr = number.ToString();
  66.  
  67.                 if (string.IsNullOrEmpty(numberStr)) coefs.Add(1);
  68.                 else if (numberStr == "-") coefs.Add(-1);
  69.                 else coefs.Add(double.Parse(numberStr, System.Globalization.CultureInfo.InvariantCulture));
  70.             }
  71.  
  72.             return SolvePolynom(coefs[0], coefs[1], coefs[2]);
  73.         }
  74.     }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement