C primer plus 第八章 练习8:

本程序提供了一个交互式菜单,用户可以选择执行加法、减法、乘法或除法操作。程序确保用户输入有效数值,并在除法操作中处理除数为零的情况。用户可以重复执行操作直到选择退出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

#include <stdio.h>
#include <windows.h>
char get_choice(void);
char get_first(void);
double panduan(void);
double panduan2(void);
int main(void)
{
    int choice;
    double x, y, ans;
    x = y = ans = 0.00;

    while ((choice = get_choice()) != 'q')
    {
        x = panduan();
        y = panduan2();
        switch (choice)
        {
        case 'a': ans = x + y; printf("%.2f + %.2f = %.2f.\n", x, y, ans); break;
        case 's': ans = x - y; printf("%.2f - %.2f = %.2f.\n", x, y, ans); break;
        case 'm': ans = x * y; printf("%.2f * %.2f = %.2f.\n", x, y, ans); break;
        case 'd': ans = x / y; printf("%.2f / %.2f = %.2f.\n", x, y, ans); break;
        }
    }

}

char get_choice(void)
{
    int ch;

    printf("Enter the operation of your choice:\n");
    printf("a. add               s. subtract\n");
    printf("m. multiply          d. divide\n");
    printf("q. quit\n");
    ch = get_first();
    while (!(ch == 'a' || ch == 's' || ch == 'm' || ch == 'd') && ch != 'q')
    {
        printf("Please enter 'a','s','m','d','q' .\n");
        ch = get_first();
    }
    printf("Bye.\n");
    system("pause");
    return ch;
}

char get_first(void)
{
    int ch;

    ch = getchar();
    while (getchar() != '\n')
        continue;
    return ch;
}

double panduan(void)
{
    char ch;
    double x;

    printf("Enter first number: ");
    while ((scanf_s("%lf", &x)) != 1)
    {
        while ((ch = getchar()) != '\n')
            putchar(ch);
        printf(" is not an integer.\nPlease enter an integer value, such as 25, -175, or 3: ");
    }
    return x;
}

double panduan2(void)
{
    char ch;
    double y;

    printf("Enter second number: ");
    while ((scanf_s("%lf", &y)) != 1)
    {
        while ((ch = getchar()) != '\n')
            putchar(ch);
        printf(" is not an integer.\nPlease enter an integer value, such as 25, -175, or 3: ");
    }
    return y;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值