【C语言】「刷题思路」 水果价格查询

原题

给定四种水果,分别是苹果(apple)、梨(pear)、桔子(orange)、葡萄(grape),单价分别对应为3.00元/公斤、2.50元/公斤、4.10元/公斤、10.20元/公斤。

首先在屏幕上显示以下菜单:

[1] apple
[2] pear
[3] orange
[4] grape
[0] exit

用户可以输入编号1~4查询对应水果的单价。当连续查询次数超过5次时,程序应自动退出查询;不到5次而用户输入0即退出;输入其他编号,显示价格为0。

输入格式:

输入在一行中给出用户连续输入的若干个编号。

输出格式:

首先在屏幕上显示菜单。然后对应用户的每个输入,在一行中按格式“price = 价格”输出查询结果,其中价格保留两位小数。当用户连续查询次数超过5次、或主动输入0时,程序结束。

输入样例1:

3 -1 0 2

输出样例1:

[1] apple
[2] pear
[3] orange
[4] grape
[0] exit
price = 4.10
price = 0.00

输入样例2:

1 2 3 3 4 4 5 6 7 8

输出样例2:

[1] apple
[2] pear
[3] orange
[4] grape
[0] exit
price = 3.00
price = 2.50
price = 4.10
price = 4.10
price = 10.20

题解 及其思路

第一步

本题要求输出价格表,但是价格表内容是固定了,不妨定义一个数组,其中包含了五个内容,所以我们先定义一个数组

float prices[] = {0.00, 3.00, 2.50, 4.10, 10.20};

再对价格表内容进行输出

 printf("[1] apple\n");
    printf("[2] pear\n");
    printf("[3] orange\n");
    printf("[4] grape\n");
    printf("[0] exit\n");

姐下来我们要对输入的内容进行输出,按照题目要求,输出的次数并不固定,但是不超过五次,且检测输入为0时停止,那么我们只需要写一个不大于五次的循环并且在循环中添加判断语句,可以写出如下代码

int input;
    int count = 0; // 记录查询次数
    while (count < 5)
     {
        if (scanf("%d", &input) != 1) { // 检查是否成功读取一个整数
            break;
        }
        if (input == 0) {
            break; // 用户选择退出
        }
        if (input >= 1 && input <= 4) {
            printf("price = %.2f\n", prices[input]);
        } else {
            printf("price = 0.00\n");
        }
        count++;
    }

最后可以得到整段代码

#include <stdio.h>

int main() {
    // 定义水果价格数组
    float prices[] = {0.00, 3.00, 2.50, 4.10, 10.20};
    // 显示菜单
    printf("[1] apple\n");
    printf("[2] pear\n");
    printf("[3] orange\n");
    printf("[4] grape\n");
    printf("[0] exit\n");

    int input;
    int count = 0; 
    while (count < 5) 
{
        if (scanf("%d", &input) != 1) { 
            break;
        }
        if (input == 0) {
            break;
        }
        if (input >= 1 && input <= 4) {
            printf("price = %.2f\n", prices[input]);
        } else {
            printf("price = 0.00\n");
        }
        count++;
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值