记录——《C Primer Plus (第五版)》第八章编程练习第八题

40 篇文章 0 订阅
 编写一个程序,显示一个菜单,为您提供加法、减法、乘法或除法的选项。获得您的选择后,该程序请求两个数,然后执行您选择的操作。该程序应该只接受它所提供的菜单选项。它应该使用float类型的数。并且如果用户未能输入数字应允许其重新输入。在出发的情况中,如果用户输入0作为第二个数,该程序应该提示用户输入一个新的值。
# include <stdio.h>

float add(float one, float two);
float sub(float one, float two);
float mul(float one, float two);
float div(float one, float two);
float get();
//bool is_enter();    //有错不明白

int main(void)
{
    float one;
    float two;
    char ch;

    printf("********计算器********\n\n");
    printf("a. add     s. subtract\n");
    printf("m. multiply  d. divide\n");
    printf("q. quit\n\n");
    printf("**********************\n");  
    while((ch = getchar()) != 'q')
    {
        switch(ch)
        {
        case 'a':
            one = get();
            two = get();
            printf("%.3f + %.3f = %.3f\n", one, two, add( one, two));
            break;
        case 's': 
            one = get();
            two = get();
            printf("%.3f - %.3f = %.3f\n", one, two, sub( one, two));
            break;
        case 'm':
            one = get();
            two = get();
            printf("%.3f * %.3f = %.3f\n", one, two, mul( one, two));
            break;
        case 'd':
            one = get();
            two = get();
            if(two == 0)
                two = get();
            printf("%.3f / %.3f = %.3f\n", one, two, div( one, two));
            break;


        }
    }

    return 0;
}

float get()
{
    float num;
    printf("Please enter a number :\n");
    while(scanf("%f", &num) != 1)
        printf("Please enter anther number :\n");

    return num;
}

float add(float one, float two)
{
    float sum;
    sum = one + two;
    return sum;
}

float sub(float one, float two)
{
    float sub;
    sub = one - two;
    return sub;
}

float mul(float one, float two)
{
    float mul;
    mul = one * two;
    return mul;
}

float div(float one, float two)
{
    float div;
    div = one / two;
    return div;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值