/*编写程序,输入用户的月用电量(千瓦时),计算并输出该用户应支付的电费(元)*/ /*月用电量 50 千瓦时以内的,电价为 0.53 元/千瓦时;超过 50 千瓦时的用电量,电价上调 0.05 元/千瓦时*/ #include<stdio.h> int main(void) { double x,y; double cylinder(double x);/*定义x y的函数*/ printf("Enter x:"); scanf("%lf",&x); if(x>0){ y=cylinder(x); printf("y=%.2f\n",y); } else { printf("错误"); } return 0; } double cylinder(double x) { double y; if(x<=50) { y=0.53*x; } else { y=26.5+0.58*(x-50); } return y; }
/*计算多个用户的电费*/ #include<stdio.h> int main(void) { int i,m; double x,y; double cylinder(double x);/*定义x y的函数*/ printf("Enter m:"); scanf("%d",&m); for(i=1;i<=m;i++) /*for语句计算多个用户的电费*/ { printf("Enter x:"); scanf("%Lf",&x); if(x<=0) printf("输入错误,重新输入"); else{ y=cylinder(x); } printf("y=%.3f\n",y ); } return 0; } double cylinder(double x) { double y; if(x<=50) { y=0.53*x; } else { y=26.5+0.58*(x-50); } return y; }
感想
一定要注意for语句中,循环个数n的输入是不能放在for语句中的,而每次循环需输入的自变量是要放进语句中的。
疑问:
自定义函数中为何要定义最后输出的函数值?如图,y不是在后面已经赋值了么?