Topic Collection of Zhejiang University Edition "C Language Programming (3rd Edition)"
Exercise 5-1 Symbolic function (10 points)
This question requires the realization of the sign function sign(x).
Function interface definition:
int sign( int x );
Among them x
is the integer parameter passed in by the user. The sign function is defined as: if x
greater than 0, sign(x)
= 1; if x
equal to 0, sign(x)
= 0; otherwise, sign(x)
= −1.
Sample referee test procedure:
#include <stdio.h>
int sign( int x );
int main()
{
int x;
scanf("%d", &x);
printf("sign(%d) = %d\n", x, sign(x));
return 0;
}
/* 你的代码将被嵌在这里 */
Input sample:
10
Sample output:
sign(10) = 1
Code implementation 1:
int sign (int x)
{
int a;
if(x>0){
a=1;
}else if(x==0){
a=0;
}else{
a=-1;
}
return a;
}
Code implementation 2:
int sign( int x ){
int flag=0;
flag = (x==0) ? 0 : ((x>0) ? 1 : -1);
return flag;
}
Submit result:
to sum up:
The ternary operator provides a shorthand way of expressing simple if-else statements. Familiar with the ternary operator and use it to reduce the amount of code and make it simple and easy to understand.