优化代码void yinliao() { int l; char d[6][40]={"海南老盐水","鸭屎香柠檬茶","斑斓香茅冰饮","豆奶","可乐/雪碧","LED气泡水"}; { float price[6]={16,18,12,9,3,9}; printf("\n"); printf("饮料推荐\n"); printf(" %-6s%-6s%\n", "\t名称 ", "\t单价\n "); printf(" %-7s%-7s%\n", "\t海南老盐水", "\t16\n"); printf(" %-7s%-7s%\n", "\t鸭屎香柠檬茶", "\t18\n"); printf(" %-7s%-7s%\n", "\t斑斓香茅冰饮", "\t12\n"); printf(" %-7s%-7s%\n", "\t豆奶", "\t9\n"); printf(" %-7s%-7s%\n", "\t可乐/雪碧", "\t3\n"); printf(" %-7s%-7s%\n", "\tLED气泡水", "\t9\n"); } }
时间: 2023-07-02 10:15:19 浏览: 121
51单片机实例190-步进电机
这段代码可以进行如下优化:
1. 使用常量来保存饮料名称和价格,避免魔法数字的使用。例如可以使用以下代码:
```c
const char* names[] = {"海南老盐水", "鸭屎香柠檬茶", "斑斓香茅冰饮", "豆奶", "可乐/雪碧", "LED气泡水"};
const float prices[] = {16.0f, 18.0f, 12.0f, 9.0f, 3.0f, 9.0f};
const int numDrinks = 6;
```
2. 使用循环来输出饮料列表。例如可以使用以下代码:
```c
printf("\n饮料推荐\n");
printf("%-10s%-10s\n", "名称", "单价");
for (int i = 0; i < numDrinks; ++i) {
printf("%-10s%-10.1f\n", names[i], prices[i]);
}
```
3. 去除不必要的大括号。例如可以使用以下代码:
```c
void yinliao() {
const char* names[] = {"海南老盐水", "鸭屎香柠檬茶", "斑斓香茅冰饮", "豆奶", "可乐/雪碧", "LED气泡水"};
const float prices[] = {16.0f, 18.0f, 12.0f, 9.0f, 3.0f, 9.0f};
const int numDrinks = 6;
printf("\n饮料推荐\n");
printf("%-10s%-10s\n", "名称", "单价");
for (int i = 0; i < numDrinks; ++i) {
printf("%-10s%-10.1f\n", names[i], prices[i]);
}
}
```
阅读全文