static void Main(string[] args) { RationalNumber rationalNumber1 = new RationalNumber(1, 4); RationalNumber rationalNumber2 = new RationalNumber(Console.ReadLine()); rationalNumber1.Print(); Console.WriteLine(rationalNumber2.ToString()); int intValue = rationalNumber1; double doubleValue = (double)rationalNumber2; Console.WriteLine("Целая часть первого числа(int): " + intValue); Console.WriteLine("Целое часть второго числа(double): " + doubleValue); Console.WriteLine((rationalNumber1 + rationalNumber2).ToString()); Console.WriteLine((rationalNumber1 - rationalNumber2).ToString()); Console.WriteLine((rationalNumber1 * rationalNumber2).ToString()); Console.WriteLine((rationalNumber1 / rationalNumber2).ToString()); Console.WriteLine(rationalNumber1 < rationalNumber2); Console.WriteLine(rationalNumber1 > rationalNumber2); Console.WriteLine(rationalNumber1 == rationalNumber2); Console.ReadKey(); }
public static RationalNumber Parse(string s) //из строки в объект { var num = double.Parse(s); // var num = Convert.ToDouble(s); var counter = 0; while (num > (int)num) { num *= 10; counter++; } var first = new BigInteger(num); var second = new BigInteger(Math.Pow(10, counter)); var m = first; var n = second; while (true) { var r = m % n; if (r == 0) { break; } m = n; n = r; } var gcd = n; first /= gcd; second /= gcd; var a = new RationalNumber((int)first, (int)second); return(a); }
public static RationalNumber operator *(RationalNumber num1, RationalNumber num2) { RationalNumber temp = new RationalNumber(); if ((num1.negative && num2.negative) || (!num1.negative && !num2.negative)) { temp.negative = false; } else { temp.negative = true; } temp.numerator = num1.numerator * num2.numerator; temp.denominator = num1.denominator * num2.denominator; int commonD = GCD(temp.numerator, temp.denominator); temp.numerator /= commonD; temp.denominator /= commonD; return(temp); }
public static void RationNumberArrFiller(ref RationalNumber[] rationNumbers) { string numberQuantityStr; WriteLine("How many numbers do you whant to create?"); numberQuantityStr = ReadLine(); if (int.Parse(numberQuantityStr) <= 0) { Write("wrong number entered"); return; } rationNumbers = new RationalNumber[int.Parse(numberQuantityStr)]; for (int i = 0; i < rationNumbers.Length; i++) { string entringNumStr; int numerator; int denumerator; for (; ;) { WriteLine("Enter numerator please"); entringNumStr = ReadLine(); if ((string.IsNullOrEmpty(entringNumStr)) || (int.Parse(entringNumStr) < 0)) { WriteLine("Wrong value was entered, " + "try again please!"); } else { numerator = int.Parse(entringNumStr); break; } } for (; ;) { WriteLine("Enter denumerator please"); entringNumStr = ReadLine(); if ((string.IsNullOrEmpty(entringNumStr)) || (int.Parse(entringNumStr) < 0)) { WriteLine("Wrong value was entered, " + "try again please!"); } else { denumerator = int.Parse(entringNumStr); break; } } rationNumbers[i] = new RationalNumber(numerator, denumerator); } }
public static RationalNumber StringToRationalNumber(string str) { RationalNumber num = new RationalNumber(); num.negative = false; str.Replace(" ", ""); if (str.Contains(".")) { str = str.Replace('.', ' '); str = str.Replace('(', ' '); str = str.Replace(')', ' '); string[] arr = str.Split(' '); if (arr.Length == 2) { int integerPart = 0; int fractionalPart = 0; try { integerPart = Convert.ToInt32(arr[0]); if (arr[0][0] == '-') { integerPart = integerPart >= 0 ? integerPart : -integerPart; num.negative = true; } fractionalPart = Convert.ToInt32(arr[1]); if (fractionalPart < 0) { throw new Exception("Unkorrect input"); } } catch { throw new Exception("Unkorrect input"); } int tempN = fractionalPart; int tempM = (int)Math.Pow(10, arr[1].Length); tempN = tempM * integerPart + tempN; int commonD = GCD(tempN, tempM); tempM /= commonD; tempN /= commonD; num.numerator = tempN; num.denominator = tempM; } else if (arr.Length == 4 && arr[3] == "") { int integerPart = 0; int fractionalPart = 0; int periodicPart = 0; try { integerPart = Convert.ToInt32(arr[0]); if (arr[0][0] == '-') { integerPart = integerPart >= 0 ? integerPart : -integerPart; num.negative = true; } if (arr[1].Length != 0) { fractionalPart = Convert.ToInt32(arr[1]); } else { fractionalPart = 0; } periodicPart = Convert.ToInt32(arr[2]); } catch { throw new Exception("Unkorrect input"); } int tempN = (fractionalPart * (int)Math.Pow(10, arr[2].Length) + periodicPart) - fractionalPart; int tempM = NinesByCount(arr[2].Length) * (int)Math.Pow(10, arr[1].Length); tempN = integerPart * tempM + tempN; int commonD = GCD(tempN, tempM); tempM /= commonD; tempN /= commonD; num.numerator = tempN; num.denominator = tempM; } } else if (str.Contains("/")) { string[] arr = str.Split('/'); int tempN = 0; int tempM = 0; try { tempN = Convert.ToInt32(arr[0]); if (arr[0][0] == '-') { tempN = tempN >= 0 ? tempN : -tempN; num.negative = true; } tempM = Convert.ToInt32(arr[1]); if (tempM == 0) { throw new Exception("Unkorrect input"); } } catch { throw new Exception("Unkorrect input"); } num.numerator = tempN; num.denominator = tempM; } else { throw new Exception("Unkorrect input"); } return(num); }
public RationalNumber(RationalNumber obj) { numerator = obj.numerator; denominator = obj.denominator; negative = obj.negative; }
static void Main(string[] args) { long a = 12; long b = 20; long c = -7; long d = 15; RationalNumber r1 = new RationalNumber(a, b); RationalNumber r2 = new RationalNumber(c, d); //математические операции Console.WriteLine("ПЕРЕКРЫТИЕ МАТЕМАТИЧЕСКИХ ОПЕРАЦИЙ\n--------------------------------"); Console.WriteLine($"Сумма дробей:\n{r1.ToString()} + ({r2.ToString()}) = " + $"{(r1 + r2).ToString()}"); Console.WriteLine($"Сумма дроби и числа:\n{r1.ToString()} + 3 = {(r1 + 3).ToString()}"); Console.WriteLine($"Сумма числа и дроби:\n2 + ({r2.ToString()}) = {(2 + r2).ToString()}"); Console.WriteLine($"Разность дробей:\n{r1.ToString()} - ({r2.ToString()}) = " + $"{(r1 - r2).ToString()}"); Console.WriteLine($"Разность дроби и числа:\n{r1.ToString()} - 3 = {(r1 - 3).ToString()}"); Console.WriteLine($"Разность числа и дроби:\n2 - ({r2.ToString()}) = {(2 - r2).ToString()}"); Console.WriteLine($"Произведение дробей:\n{r1.ToString()} * ({r2.ToString()}) =" + $" {(r1 * r2).ToString()}"); Console.WriteLine($"Произведение дроби и числа:\n{r1.ToString()} * 3 = {(r1 * 3).ToString()}"); Console.WriteLine($"Произведение числа и дроби:\n2 * {r2.ToString()} = {(2 * r2).ToString()}"); try { Console.WriteLine($"Деление дробей:\n{r1.ToString()} / ({r2.ToString()}) =" + $" {(r1 / r2).ToString()}"); Console.WriteLine($"Деление дроби на число:\n{r1.ToString()} / 3 = {(r1 / 3).ToString()}"); Console.WriteLine($"Деление числа на дробь:\n2 / {r2.ToString()} = {(2 / r2).ToString()}"); } catch (DivideByZeroException) { Console.WriteLine("ОШИБКА! Деление на ноль"); } Console.WriteLine($"Противоположная дробь:\n{r1.ToString()} -> {(-r1).ToString()}"); Console.WriteLine($"Инкремент:\n++({r1.ToString()}) -> {(++r1).ToString()}"); Console.WriteLine($"Декремент:\n--({r1.ToString()}) -> {(--r1).ToString()}"); //операции сравнения Console.WriteLine("\nПЕРЕКРЫТИЕ ОПЕРАЦИЙ СРАВНЕНИЯ\n--------------------------------"); Console.WriteLine($"Сравнение дробей(==,!=):\n{r1.ToString()} {EqualZn(r1, r1)} {r1.ToString()}"); Console.WriteLine($"{r1.ToString()} {EqualZn(r1, r2)} {r2.ToString()}"); Console.WriteLine($"Сравнение дробей(>,<,>=,<=):\n{r1.ToString()} {Znak(r1, r1)} {r1.ToString()}"); Console.WriteLine($"{r2.ToString()} {Znak(r2, r1)} {r1.ToString()}"); Console.WriteLine($"Сравнение дроби с числом(==,!=):\n{r1.ToString()} {EqualZn(r1, -3)} -3"); Console.WriteLine($"Сравнение дроби с числом(>,<,>=,<=):\n{r1.ToString()} {Znak(r1, 5)} 5"); // явные и неявные операторы преобразования RationalNumber r3 = new RationalNumber(-4, 3); Console.WriteLine("\nПРЕОБРАЗОВАНИЕ ТИПОВ\n--------------------------------"); Console.WriteLine($"В int {r3.ToString()} -> {(int)r3}"); Console.WriteLine($"В long {r3.ToString()} -> {(long)r3}"); Console.WriteLine($"В double {r3.ToString()} -> {(double)r3}"); Console.WriteLine($"В decimal {r3.ToString()} -> {(decimal)r3}"); r3 = 25; Console.WriteLine($"Из int 25 -> {r3}"); r3 = 154L; Console.WriteLine($"Из long 154 -> {r3}"); r3 = 2.5; Console.WriteLine($"Из double 2.5 -> {r3}"); r3 = 0.2225m; Console.WriteLine($"Из decimal 0.2225 -> {r3}"); //представление в виде строки в различных форматах Console.WriteLine("\nПРЕДСТАВЛЕНИЕ ДРОБИ В ВИДЕ СТРОКИ\n-----------------------------------"); Console.WriteLine("1 вариант: " + r1.DifferentStrings('.')); Console.WriteLine("2 вариант: " + r1.DifferentStrings(',')); Console.WriteLine("3 вариант: " + r1.DifferentStrings('/')); // получение объекта класса по строковому представлению из разных форматов Console.WriteLine("\nПОЛУЧЕНИЕ ДРОБИ ПО СТРОКОВОМУ ПРЕДСТАВЛЕНИЮ" + "\n--------------------------------------------"); do { r3 = RationalNumber.TakeFromStrings(); r3.ReducedFraction(); Console.WriteLine($"\nВаше число, преобразованное в дробь: {r3.ToString()}"); Console.WriteLine("\nХотите повторить ввод?(нет - 0, да - любая клавиша)"); } while (Console.ReadLine() != "0"); }
static void Main(string[] args) { bool exit = false; ArrayList numbers = new ArrayList(); while (true) { RationalNumber r1, r2, result; Console.WriteLine("Write two rational numbers in one of these formats: " + "\na/b" + "\na,bcd..."); Console.Write("\n\nThe first one: "); if (!RationalNumber.Extraction(Console.ReadLine(), out r1)) { Console.WriteLine("Error. Wrong input"); break; } numbers.Add(r1); Console.Write("The second: "); if (!RationalNumber.Extraction(Console.ReadLine(), out r2)) { Console.WriteLine("Error. Wrong input"); break; } numbers.Add(r2); Console.Clear(); Console.WriteLine("What do you want to do?" + "\n1.Add one to another" + "\n2.Substract one from another" + "\n3.Multiply these numbers" + "\n4.Divide one by another" + "\n5.Compare these numbers" + "\n6.Convert to int and double" + "\n7.Sort all entered numbers" + "\n9.Exit the program"); int K; if (!Int32.TryParse(Console.ReadLine(), out K)) { Console.WriteLine("Error. Wrong input"); break; } Console.Clear(); switch (K) { case 1: { result = r1 + r2; Console.WriteLine(result.ToStringFormat1()); Console.WriteLine(result.ToStringFormat2()); break; } case 2: { result = r1 - r2; Console.WriteLine(result.ToStringFormat1()); Console.WriteLine(result.ToStringFormat2()); break; } case 3: { result = r1 * r2; Console.WriteLine(result.ToStringFormat1()); Console.WriteLine(result.ToStringFormat2()); break; } case 4: { result = r1 / r2; Console.WriteLine(result.ToStringFormat1()); Console.WriteLine(result.ToStringFormat2()); break; } case 5: { if (r1 > r2) { Console.WriteLine($"{r1.ToStringFormat1()} > {r2.ToStringFormat1()}" + $"\n{r1.ToStringFormat2()} > {r2.ToStringFormat2()}"); } if (r1 >= r2) { Console.WriteLine($"{r1.ToStringFormat1()} >= {r2.ToStringFormat1()}" + $"\n{r1.ToStringFormat2()} >= {r2.ToStringFormat2()}"); } if (r1 < r2) { Console.WriteLine($"{r1.ToStringFormat1()} < {r2.ToStringFormat1()}" + $"\n{r1.ToStringFormat2()} < {r2.ToStringFormat2()}"); } if (r1 <= r2) { Console.WriteLine($"{r1.ToStringFormat1()} <= {r2.ToStringFormat1()}" + $"\n{r1.ToStringFormat2()} <= {r2.ToStringFormat2()}"); } if (r1 == r2) { Console.WriteLine($"{r1.ToStringFormat1()} = {r2.ToStringFormat1()}" + $"\n{r1.ToStringFormat2()} = {r2.ToStringFormat2()}"); } if (r1 != r2) { Console.WriteLine($"{r1.ToStringFormat1()} != {r2.ToStringFormat1()}" + $"\n{r1.ToStringFormat2()} != {r2.ToStringFormat2()}"); } break; } case 6: { int a = r1, b = r2; Console.WriteLine($"r1 int : {a}" + $"\nr1 double : {(double)r1}" + $"\nr2 int : {b}" + $"\nr2 double : {(double)r2}"); break; } case 7: { numbers.Sort(); foreach (RationalNumber r in numbers) { Console.WriteLine($"{r.ToStringFormat2()}"); } break; } case 9: { exit = true; break; } } if (exit) { break; } Console.WriteLine("Press any key to return..."); Console.ReadKey(); Console.Clear(); } }