C程序设计 (第四版) 谭浩强 习题4.6
有一个函数:
y { x ( x < 1 ) 2 x − 1 ( 1 ≤ x < 10 ) 3 x − 11 ( x ≥ 10 ) y \begin {cases}x&(x < 1)\\ 2x - 1&(1 \leq x < 10)\\ 3x - 11&(x \geq 10)\end {cases} y⎩ ⎨ ⎧x2x−13x−11(x<1)(1≤x<10)(x≥10)
写程序,输入x的值,输出y相应的值。
IDE工具:VS2010
Note: 使用不同的IDE工具可能有部分差异。
代码块
方法1:使用选择结构语句
#include <stdio.h>
#include <stdlib.h>
int main(){
int x, y;
printf("Enter X Value: ");
scanf_s("%d", &x);
if(x < 1){
y = x;
}
else if(x >= 1 && x < 10){
y = 2 * x -1;
}
else{
y = 3 * x - 11;
}
printf("Y Value = %d\n", y);
system("pause");
return 0;
}
方法2:使用条件表达式、指针、函数的模块化设计
#include <stdio.h>
#include <stdlib.h>
void input(int *x){
printf("Enter X Value: ");
scanf_s("%d", x);
}
int yValue(int *x){
return *x < 1 ? *x : (*x < 10 ? *x * 2 - 1 : *x * 3 - 11);
}
void output(int *x){
printf("Y Value = %d\n", yValue(x));
}
int main(){
int *x = (int*)malloc(sizeof(int));
input(x);
output(x);
free(x);
system("pause");
return 0;
}