C语言设计 (第四版) 谭浩强 例4.5
有一函数:
y = { − 1 ( x < 0 ) 0 ( x = 0 ) 1 ( x > 0 ) y = \begin{cases}-1\ (x \lt 0)\\0\ \ \ \ (x = 0)\\1\ \ \ \ (x \gt 0)\end{cases} y=⎩ ⎨ ⎧−1 (x<0)0 (x=0)1 (x>0)
编一程序,输入一个x值,要求输出相应的y值。
IDE工具:VS2010
Note: 使用不同的IDE工具可能有部分差异。
代码块
方法1:条件语句
#include <stdio.h>
#include <stdlib.h>
#define FORMAT "%d"
typedef int Type;
int main(){
Type x;
int y;
printf("Enter X Value: ");
scanf_s(FORMAT, &x);
if(x < 0){
y = -1;
}
else if(x == 0){
y = 0;
}
else{
y = 1;
}
printf("Y Value = ");
printf(FORMAT, y);
printf("\n");
system("pause");
return 0;
}
方法2:使用函数的模块化设计
#include <stdio.h>
#include <stdlib.h>
#define FORMAT "%d"
typedef int Type;
void input(Type *x){
printf("Enter X Value: ");
scanf_s(FORMAT, x);
}
void output(Type *x){
int y = *x > 0 ? 1 : (*x == 0 ? 0 : -1);
printf("Y Value = ");
printf(FORMAT, y);
printf("\n");
}
int main(){
Type *x = (Type*)malloc(sizeof(Type));
input(x);
output(x);
free(x);
system("pause");
return 0;
}