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

/*利用循环计算多个圆柱体体积*/

#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; }

  

posted @ 2013-10-17 09:14  墨墨萧萧  阅读(214)  评论(0)    收藏  举报