简体   繁体   中英

problem with if-statement and negative integer

Really new to C#. I want to check if an integer (input from user) is positive, negative or zero. It works with the positive number and zero but not when I input a negative number!

I've tried to change input type from user to int, float, decimal, double and so on but nothing works. Also tried a switch-statement. I´m using Visual Studio and debugging to Mac terminal, can that be the issue? I can use negative numbers when writing other code, such as math problems and so on.

Console.Write("Enter a number: ");   
int number = int.Parse(Console.ReadLine());   
if (number == 0)   
{
     Console.Write("zero");
}
else if (number < 0)
{
    Console.Write("negative");
}
else
{       
     Console.Write("positive");

(I've also tried with a switch-statement:)

Console.Write("Enter a number: ");
int number = int.Parse(Console.ReadLine());
switch(number)   
{   
     case 0: Console.Write("zero"); break;    
     case -1: Console.Write("negative"); break;    
     case 1: Console.Write("positive"); break;    
}

In both cases I get the right output when entering a positive number or 0 but when entering a negative number I get error message: "input string was not in a correct format"

It should work because int here is Int32 range is -2,147,483,648 to 2,147,483,647. If you are entering any number within this range, it should work. For number outside this range you will get "value too small or too large". Please share the number you are entering

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