C //习题 4.6 有一个函数:。。。 写程序,输入x的值,输出y相应的值。

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 x2x13x11(x<1)(1x<10)(x10)

写程序,输入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;
}
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Navigator_Z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值