How to invert a positive number to negative and vice versa in C#?

Asked

Viewed 875 times

2

How do I get the number typed by the user, whether positive or negative, reversed?

using System;

namespace POOTeste
{
    class Program2
    {
        static int Main(string[] args)
        {
            int numero;
            Console.Write("Digite um número positivo ou negativo: ");
            numero = int.Parse(Console.ReadLine());
            Console.Write($"O valor inverso é {numero}");
            Console.ReadKey();
            return 0;
        }
    }
}
  • You can multiply by -1 to reverse its value, and check if it is negative with < 0.

1 answer

2


Placing the equal negative sign (-) in mathematics. It also seems that you have not yet learned to pick up a number typed correctly, as I have answered you before (it can give a more significant error message or make a loop to ask again if the person has typed something wrong). Then the right thing would be:

using static System.Console;

namespace POOTeste {
    public class Program2 {
        public static int Main() {
            Write("Digite um número positivo ou negativo: ");
            if (!int.TryParse(ReadLine(), out var numero)) return 1;
            Write($"O valor inverso é {-numero}");
            return 0;
        }
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

Browser other questions tagged

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