Task: Calculate the value of the function at a given point. Use the simplest functions of the form Y = 3 - X + 2 * X * X * X, which do not involve the calculation of the sum of a series or the use of recurrent formulas.

The task is very simple. I implemented the logic.

The question is different: in what ways can I repeat the conditions in the program, so that before entering X and after output Y, the program will ask the user to either press a certain number (ie, X) or press a letter (let's say ' q '), which will be a way out of the program. And so that such a request appears, of course, after each output "y" exactly until I enter "q"

I thought to do something like this while loop, or recursion, or both.

However, he did not come to anything intelligible. I do not really understand how all this can be implemented here.

Here is my code.

using System; namespace ConsoleApp2 { class Program { static void Main(string[] args) { Console.WriteLine("Hello, this program calculates the value of the function \"y = 3 – x + 2 * x * x * x\"!"); Console.WriteLine("Please, choose any number or \"q\" to exit this programm."); string a = Console.ReadLine(); if (a == "q") { return; // здесь я решил сделать выход из программы через return, ибо другого способа не нагуглил } else { int x = Convert.ToInt32(a); int y = 3 - x + (2 * x * x * x); Console.WriteLine("The value of the function for x=" + x + " is " + y); Console.ReadLine(); } } } } 

Actually, what can you advise?

    3 answers 3

    I am ashamed not to know about the cycle with a precondition

     var str = Console.ReadLine(); while (str != "q") { /*здесь парсите и проверяете ввод, делаете все что вам нужно*/ str = Console.ReadLine(); } 
       using System; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { int x; Console.WriteLine("Программа по формуле \"y = 3 – x + 2 * x * x * x\"!"); do { Console.Write("Введите значения:"); x = Convert.ToInt32(Console.ReadLine()); int y = 3 - x + (2 * x * x * x); Console.WriteLine("Значения x=" + x + " is " + y); Console.WriteLine("Повторить? y/n"); } while(Console.ReadKey(true).Key == ConsoleKey.Y); } } 
      • He advised that he knew himself :) If your option is better, then I will use it in the future. - Petr
      • thanks for the advice :) - Petr

      Just wrap in an endless loop?

       static void Main(string[] args) { while(true) { ... if (a == "q") { return; } else ... } } 
      • Why such a poorly readable construction? You still GoTo offer. - Sergey
      • As for me, more readable than a recurring call to Console.ReadLine() . - arrowd September
      • He will be in your case. Data from somewhere must be taken new. - Sergey