练习3-8 查询水果价格 (15分)

练习3-8 查询水果价格 (15分)

给定四种水果,分别是苹果(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

#include<stdio.h>

int main()
{
	printf("[1] apple\n[2] pear\n[3] orange\n[4] grape\n[0] exit\n");
	int count = 0;
	int index;
	
	while(1)
	{
		scanf("%d",&index);
		if(index == 0)
			return 0;
		else if(index>=1&&index<=4)
		{
			
			switch(index)
			{
				case 1:printf("price = 3.00\n");break;
				case 2:printf("price = 2.50\n");break;
				case 3:printf("price = 4.10\n");break;
				case 4:printf("price = 10.20\n");break;
				default:break;
			}
			count++;
			if(count>=5)
			return 0;
			
		}
		else
		{
			count++;
			printf("price = 0.00\n");
			if(count>5)
			return 0;
		}
	}
	
	return 0;
}
根据提供的信息,这里有一个编程练习题目关于查询水果价格。这个例子通常用于教学目的,特别是针对初学者教授条件语句和循环结构的使用。下面是一个Python版本的例子来实现这一功能。 ```python def query_fruit_price(): # 定义水果及其对应的单价 fruit_prices = { 1: (&#39;苹果&#39;, 3), # 假设苹果的价格3元/个 2: (&#39;梨子&#39;, 2), # 假设梨子的价格为2元/个 3: (&#39;橙子&#39;, 4), # 假设橙子的价格为4元/个 4: (&#39;葡萄&#39;, 5) # 假设葡萄的价格为5元/串 } count = 0 while True: if count >= 5: print("已达到最大查询次数,程序即将退出。") break try: choice = int(input("请输入要查询水果编号 (1-苹果, 2-梨子, 3-橙子, 4-葡萄, 0-退出): ")) if choice == 0 or not (1 <= choice <= 4): if choice != 0: print("无效的选择,价格为0.") print("感谢您的使用!再见。") break name, price = fruit_prices.get(choice) print(f"您选择的是 {name} ,其单价是 {price} 元。") except ValueError: print("输入错误,请输入正确的数字编号。") finally: count += 1 query_fruit_price() ``` 这段代码定义了一个函数`query_fruit_price()`,它会提示用户输入想要查询水果编号,并输出相应的单价直到用户决定停止或者达到了预设的最大查询次数限制(这里是5次)。如果用户输入了有效的编号,则返回相应水果的名字和价格;若输入非有效值则提醒用户重新输入或告知价格为零;当用户输入&#39;0&#39;时,程序结束运行。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值