实验四 在分支循环结构中调用自定义函数

本文介绍了使用C语言实现圆柱体体积计算及电费计算的方法。通过循环结构处理多个输入,并利用自定义函数提高代码复用性和清晰度。具体包括圆柱体体积计算公式和分段计费方案。
/*利用循环计算多个圆柱体体积*/

#include<stdio.h> int main(void) { int n,i; double v,r,h; //自定义函数声明,计算圆柱体体积

double cylinder(double r,double h); printf("Enter n:"); scanf("%d",&n); for(i=1;i<=n;i++){ printf("Enter r and h:"); scanf("%Lf%Lf",&r,&h); if(r<=0||h<=0){ printf("It is wrong"); } else if(r>0&&h>0){  v=cylinder(r,h); printf("v=%.3f\n",v); } } return 0; } double cylinder(double r,double h) { double result; result=3.14*r*r*h; return result; }

  

/*输入用户的月用电量(千瓦时),计算并输出该用户应支付的电费(元)*/

#include<stdio.h> int main(void) { int i,n; double x,y; printf("Enter n:"); scanf("%d",&n); for(i=1;i<=n;i++) { printf("Enter x:"); scanf("%Lf",&x); if(x<=0) { printf("It is wrong"); } else if(x<=50) { y=0.53*x; } else { y=50*0.53+0.58*(x-50); } printf("y=%.2f\n",y); } return 0; }

  

/*将上题的电费计算过程放到自定义函数中*/
#include<stdio.h> int main() { int i,m; double x,y;
//自定义函数声明,计算用电量 double fact(double x); double function(double x); printf("Enter m:"); scanf("%d",&m); for(i=1;i<=m;i++){ printf("Enter x:"); scanf("%Lf",&x); if(x<=0){ printf("It is wrong"); } else if(x<=50) { y=fact(x); } else { y=function(x); } printf("y=%.2f\n",y); } return 0; } double fact(double x) { double result; result=0.53*x; return result; } double function(double x) { double result; result=50*0.53+(x-50)*0.58; return result; }

  

转载于:https://www.cnblogs.com/zhangyuting/p/3373356.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值