用函数的思想进行四则运算

#include <stdio.h>

//说明
//1. 函数名 cal
//2. 有返回值 double
//3. 形参列表为 (int n1, int n2, char oper) 
//4. 在函数中,我们使用的变量名需要和形参列表中的变量名一样
double cal(int n1, int n2, char oper) {

	//定义一个变量 res ,保存运算的结果
	double res = 0.0;

	switch(oper) {
	case '+' :
		res = n1 + n2;
		break;
	case '-':
		res = n1 - n2;
		break;
	case '*':
		res = n1 * n2;
		break;
	case '/':
		res = n1 / n2;
		break;
	default :
		printf("你的运算符有误~");
	}
	printf("\n%d %c %d = %.2f\n", n1, oper, n2, res);
	return res;
}

void main() {

	int num1 = 10; //第一个数
	int num2 = 20;//第二个数
	double res = 0.0;//结果
	char oper = '-'; //运算符

	//我们又要接收两个数和一个运算符
	int num3 = 60;
	int num4 = 80;
	double res2 = 0.0;
	char oper2 = '*';

	printf("使用函数来解决计算任务~~");
	//使用函数来完成两个计算任务

	res = cal(num1, num2, oper); //调用函数,使用函数

	printf("\n cal 函数返回的结果 res=%.2f\n", res);

	//使用函数完成第二个计算任务
	res2 = cal(num3, num4, oper2); //调用函数,使用函数
	printf("\n cal 函数返回的结果 res2=%.2f\n", res2);

	getchar();
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值