c语言题目:以下 4 种⽔果的单价分别是3.00 元/公⽄,2.50 元/公⽄,4.10 元/公⽄,10.20 元/公⽄,
作者:野牛程序员:2023-12-05 09:29:34C语言阅读 2811
c语言题目:以下 4 种⽔果的单价分别是3.00 元/公⽄,2.50 元/公⽄,4.10 元/公⽄,10.20 元/公⽄,要求:本题分别⽤if 语句和switch 语句实现。 [1] apples [2] pears [3] oranges [4] grapes
输入对应的编号,查出水果价格
使用if语句:
#include <stdio.h> int main() { int choice; double price; printf("请输入水果编号:\\n"); scanf("%d", &choice); if (choice == 1) { price = 3.00; } else if (choice == 2) { price = 2.50; } else if (choice == 3) { price = 4.10; } else if (choice == 4) { price = 10.20; } else { printf("无效的选择\\n"); return 1; } printf("所选水果的单价为 %.2f 元/公斤\\n", price); return 0; }
使用switch语句:
#include <stdio.h> int main() { int choice; double price; printf("请输入水果编号:\\n"); scanf("%d", &choice); switch (choice) { case 1: price = 3.00; break; case 2: price = 2.50; break; case 3: price = 4.10; break; case 4: price = 10.20; break; default: printf("无效的选择\\n"); return 1; } printf("所选水果的单价为 %.2f 元/公斤\\n", price); return 0; }
这两个程序都实现了根据用户输入的水果编号选择相应的水果单价,并输出单价。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
