dimanche 21 avril 2019

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"

Aucun commentaire:

Enregistrer un commentaire