What is the usage of the sign function in the C language?

In the C language, the sign function is typically used to return the sign of a number, determining if it is positive, negative, or zero. Its prototype is defined as:

int sign(int x);

The parameter x is the number for which the sign needs to be determined, and the function returns:

  1. Return 1 if x is greater than 0.
  2. If x is equal to 0, return 0.
  3. If x is less than 0, return -1.

The sample code is shown below:

#include <stdio.h>

int sign(int x){
    if(x > 0){
        return 1;
    }else if(x == 0){
        return 0;
    }else{
        return -1;
    }
}

int main(){
    int num = 10;
    
    printf("The sign of %d is: %d\n", num, sign(num));
    
    num = -5;
    printf("The sign of %d is: %d\n", num, sign(num));
    
    num = 0;
    printf("The sign of %d is: %d\n", num, sign(num));
    
    return 0;
}

The output result is:

The sign of 10 is: 1
The sign of -5 is: -1
The sign of 0 is: 0
Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds