Задать контролируемый ввод значений - C#
Формулировка задачи:
как задать контролируемый ввод значений
в данном случае обязательно больше нуля, возможно связать еще и существование треугольника с try catch?
Листинг программы
- static void Main(string[] args)
- {
- try
- {
- Console.Write("ввод стороны x:");
- uint x = Convert.ToUInt32(Console.ReadLine());
- Console.Write("ввод стороны y:");
- uint y = Convert.ToUInt32(Console.ReadLine());
- Console.Write("ввод стороны z:");
- uint z = Convert.ToUInt32(Console.ReadLine());
- if (x + y < z || x + z < y || y + z < x)
- {
- Console.WriteLine("такого треугольника нет");
- }
- }
- catch (FormatException)
- {
- Console.WriteLine("не входит в диапазон значений");
- }
- }
тут только через Exception получается
да и если нули представлять как стороны не подходит
Решение задачи: «Задать контролируемый ввод значений»
textual
Листинг программы
- namespace ConsoleApplication
- {
- static class Extensions
- {
- public static int? BoundedParse(this string str, int lower, int upper)
- {
- if (str == null)
- return null;
- int result;
- bool success;
- success = int.TryParse(str, out result);
- if (!success)
- return null;
- if (result < lower)
- return null;
- if (result > upper)
- return null;
- return result;
- }
- }
- class Program
- {
- static int PromptForNumber(string prompt, int lower, int upper)
- {
- int? choice;
- do
- {
- Console.WriteLine(prompt);
- choice = Console.ReadLine().BoundedParse(lower, upper);
- }
- while (choice == null);
- return choice.Value;
- }
- static void Main()
- {
- string s = Console.ReadLine();
- int upper = 10;
- int lower = 1;
- int res = PromptForNumber(s, lower, upper);
- }
- }
- }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д