How to limit the highest numerical value to be typed in C#?

Asked

Viewed 47 times

0

I wish I had a maximum number in charge: salario = Convert.Todouble (Console.Readline()); Example: if you pass 4000 you will be invalid.

  • 1

    Do not do as the answer below, this form is wrong, even if it seems to work. A better example: https://answall.com/a/471939/101. Actually questions like this (which are not stated that the person only asks to do the code) have in dozens here on the site, would only search, example: https://answall.com/q/336749/101. Note that this solves other problems. Other form: https://answall.com/q/348157/101

1 answer

2

There are several ways to solve this problem. In this case, as you are requesting a user input, an option would be to place a condition within a loop, preventing the loop from ending while the user does not place a value within the range you need. For example:

Console.WriteLine ("entre o valor:");
       double salario = -1;
       do {
           salario = Convert.ToDouble (Console.ReadLine());
           if (salario > 4000) {
               Console.WriteLine("salário deve ser menor que 4000...");
               salario = -1;
           }
       } while (salario == -1);
      
    
       Console.WriteLine("salario={0}",salario);
  • If the user type to the letter instead of a number, what happens?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.