函数定义的抉择 (封装的抉择)--- 圆形体积计算器

思路一:封装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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值