C language programming (third edition) He Qinming exercises 5-1
Article Directory
topic
Use the function to calculate the value of the piecewise function: input x, calculate and output the value of the following piecewise function f(x).
It is required to define and call the function sign (x) to realize this piecewise function. Try to write the corresponding program.
Analysis process
enter
Condition: Enter x
Output
Condition: output the value of the piecewise function f(x)
Code
#include <stdio.h>
#include <math.h>
int sign(int x);/*函数声明*/
int main () {
/*定义变量*/
int x; /*定义变量,存储输入的n*/
/*赋值*/
printf("请输入x:\n"); /*输入提示*/
scanf("%d \n", &x); /*输入并赋给变量*/
printf("sign(%d)=%d \n", x, sign(x)); /*调用函数,输出计算结果*/
return 0;
}
int sign(int x){
if(x<0) return -1;/*x小于0时,返回-1*/
else if(x==0) return 0;/*x等于0时,返回0*/
else return 1;/*x大于0时,返回1*/
}