思路一:封装n,定义一个关于n的函数。
结果:测试不通过,但自己的电脑通过
函数定义:
double round(int n)
{
double r, h;
double v;
switch(n)
{
case 1:printf("Please enter the radius:");
scanf("%lf", &r);
v = 3.1415926535 * 4 *r *r *r / 3;
return v;
break;
case 2:printf("Please enter the radius and the height:");
scanf("%lf %lf", &r, &h);
v = 3.1415926535 * r *r *h;
return v;
break;
case 3:printf("Please enter the radius and the height:");
scanf("%lf %lf", &r, &h);
v = 3.1415926535 * r *r *h /3;
return v;
break;
default: break;
}
}
#include <stdio.h>
int main()
{
int n;
while(1)
{
printf("1-Ball\n");
printf("2-Cylinder\n");
printf("3-Cone\n");
printf("other-Exit\n");
printf("Please enter your command:\n");
scanf("%d", &n);
printf("%.2f\n", round(n));
}
return 0;
}
思路二:封装计算各体积函数,条件判断在主调函数中进行
#include <stdio.h>
double sp(double r);
double cy(double r, double h);
double f(double r, double h);
int main()
{
int n;
double r, h;
while (1)
{
printf("1-Ball\n");
printf("2-Cylinder\n");
printf("3-Cone\n");
printf("other-Exit\n");
printf("Please enter your command:\n");
scanf("%d", &n);
if (n < 1 || n > 3)
{
break;
}
if (n == 1)
{
printf("Please enter the radius:\n");
scanf("%lf", &r);
printf("%.2f\n", sp(r));
}
else if (n == 2)
{
printf("Please enter the radius and the height:\n");
scanf("%lf %lf", &r, &h);
printf("%.2f\n", cy(r, h));
}
else if (n == 3)
{
printf("Please enter the radius and the height:\n");
scanf("%lf %lf", &r, &h);
printf("%.2f\n", f(r, h));
}
}
}
函数:
double sp(double r)
{
double s;
s = 3.1415926535 * r * r * r * 4 / 3; /* 乘号写在前, 除号写在后 */
return s;
}
double cy(double r, double h)
{
double s;
s = 3.1415926535 * r * r * h;
return s;
}
double f(double r, double h)
{
double s;
s = cy(r, h) / 3;
return s;
}