A function to return a sign

前端 未结 8 1293
春和景丽
春和景丽 2021-01-17 08:40

I know this will really turn out to be simple, but my brain is just not working. I need a function in C# that will return -1 if the integer passed to the function has a nega

相关标签:
8条回答
  • 2021-01-17 09:17
    public int SignFunction(int number) 
    {
        return number.CompareTo(0);
    }
    
    0 讨论(0)
  • 2021-01-17 09:19

    This is already in the framework. Just use Math.Sign...

    int sign = Math.Sign(-82); // Should return -1
    int sign2 = Math.Sign(197); // Should return 1
    int sign3 = Math.Sign(0);   // Should return 0
    

    In addition, it will work with:

    int sign4 = Math.Sign(-5.2); // Double value, returns -1
    int sign5 = Math.Sign(0.0m); // Decimal, returns 0
    // ....
    
    0 讨论(0)
提交回复
热议问题