问题分析:
我们需要编写一个程序,根据用户输入的水果编号查询对应水果的单价,并按照要求输出结果。主要的步骤包括:
1. 定义水果数组和价格数组;
2. 显示菜单;
3. 循环接受用户输入的编号并查询对应的价格;
4. 根据查询结果进行输出;
5. 判断退出条件。
C++代码实现:
- #include <iostream>
- #include <iomanip>
- using namespace std;
- int main() {
- string fruits[4] = {"apple", "pear", "orange", "grape"};
- double prices[4] = {3.00, 2.50, 4.10, 10.20};
-
- cout << "[1] apple\n[2] pear\n[3] orange\n[4] grape\n[0] exit" << endl;
- int count = 0;
- int num;
- while (count < 5) {
- cin >> num;
-
- if (num == 0) {
- break;
- } else if (num >= 1 && num <= 4) {
- cout << "price = " << fixed << setprecision(2) << prices[num-1] << endl;
- count++;
- } else {
- cout << "price = 0.00" << endl;
- }
- }
-
- return 0;
- }
复制代码
解题思路:
首先,我们使用字符串数组
fruits 存储水果的名称,使用浮点数数组
prices 存储水果的单价。
然后,我们显示菜单选项。
接下来,使用一个循环来接受用户的输入。如果用户输入的是 0,则跳出循环;如果用户输入的是 1、2、3 或 4,则输出对应水果的单价,并将查询次数
count 加一;如果用户输入的不是上述几个数字,则输出价格为 0.00。
最后,程序结束。
希望能对你有所帮助!如果你还有其他问题,请随时提问。
球一个最佳答案谢谢啦!这对我非常重要!

