简体   繁体   中英

How to change the sign to a decimal number in C#

I need a console app that changes the sign to a certain typed number. You type 10, it gives you -10. And so on. I've managed to do that, but I can't do it if I type 1.5 for example. Or any decimal number. I get "Input string was not in a correct format". this is what I did.

string inputData = Console.ReadLine();
int a = Convert.ToInt32 (inputData);
int b = a * (-1);
Console.WriteLine(b);
Console.ReadLine();
  1. You need to use decimal as a variable type if you want to work with decimal numbers
  2. If so, use Convert.ToDecimal instead of ToInt32
  3. You don't really need to use multiplication here, it's enough just to use -a instead
string inputData = Console.ReadLine();
decimal a = Convert.ToDecimal (inputData);
decimal b = -a;
Console.WriteLine(b);
Console.ReadLine();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM