习题5-1 符号函数

本题要求实现符号函数sign(x)。
函数接口定义:

  1. int sign( int x );

其中x是用户传入的整型参数。符号函数的定义为:若x大于0,sign(x) = 1;若x等于0,sign(x) = 0;否则,sign(x) = −1。
裁判测试程序样例:

  1. #include <stdio.h>
  2. int sign( int x );
  3. int main()
  4. {
  5. int x;
  6. scanf("%d", &x);
  7. printf("sign(%d) = %d\n", x, sign(x));
  8. return 0;
  9. }
  10. /* 你的代码将被嵌在这里 */

输入样例:

10

输出样例:

sign(10) = 1

解题思路if-else 判断输出

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

运行结果

Case Hint Result Score Run Time Memory
0 sample等价,正数 Accepted 4 2 ms 356 KB
1 负数 Accepted 4 2 ms 384 KB
2 Accepted 2 2 ms 368 KB