|
楼主 |
发表于 2017-12-27 15:13:31
|
显示全部楼层
- #include <stdio.h>
- #include <string.h>
- typedef struct
- {
- char name[20];
- union
- {
- double price;
- double number;
- } u;
- } Vegetable;
- double CalculatePrice(Vegetable *v)
- {
- int i;
- const Vegetable veg[] =
- {
- {"番茄", 3.7},
- {"芥蓝", 7 },
- {"西芹", 1.3},
- {"空心菜", 8 },
- {"洋葱", 2.4},
- {"油菜", 9 },
- {"黄瓜", 6.3},
- {"白萝卜", 0.5}
- };
- const int vegLength = sizeof(veg) / sizeof(veg[0]);
- double price;
-
- for(int i = 0; i < vegLength; i++)
- {
- if(strcmp(veg[i].name, v->name) == 0)
- {
- price = veg[i].u.price * v->u.number;
- break;
- }
- }
- return price;
- }
- int GetInput(Vegetable *v)
- {
- scanf("%s", v->name);
- if(strncmp(v->name, "#", 1) == 0) // 输入#停止录入
- return 1;
- scanf("%d", &v->u.number);
- return 0;
- }
- int main(int argc, char *argv[])
- {
- Vegetable v;
- double totalPrice = 0;
- //printf("\n"); // 这里还需要提示些什么,但我实在想不出该提示些什么 ^_^
- printf("蔬菜名 数量(千克)\n");
- while(1)
- {
- if(GetInput(&v))
- break;
- totalPrice += CalculatePrice(&v);
- }
- printf("需要支付:%.2lf元\n", totalPrice);
- return 0;
- }
复制代码
按照您说的改了。不知是我没改对,还是什么原因,在不加.c后缀的文件里面运行,应该是C++了吧。还是报错。
我看报错的信息应该是重复定义。所以把int i;又去掉了,然后就能运行了。
谢谢您解答小白的疑惑。
- #include <stdio.h>
- #include <string.h>
- typedef struct
- {
- char name[20];
- union
- {
- double price;
- double number;
- } u;
- } Vegetable;
- double CalculatePrice(Vegetable *v)
- {
-
- const Vegetable veg[] =
- {
- {"番茄", 3.7},
- {"芥蓝", 7 },
- {"西芹", 1.3},
- {"空心菜", 8 },
- {"洋葱", 2.4},
- {"油菜", 9 },
- {"黄瓜", 6.3},
- {"白萝卜", 0.5}
- };
- const int vegLength = sizeof(veg) / sizeof(veg[0]);
- double price;
-
- for(int i = 0; i < vegLength; i++)
- {
- if(strcmp(veg[i].name, v->name) == 0)
- {
- price = veg[i].u.price * v->u.number;
- break;
- }
- }
- return price;
- }
- int GetInput(Vegetable *v)
- {
- scanf("%s", v->name);
- if(strncmp(v->name, "#", 1) == 0) // 输入#停止录入
- return 1;
- scanf("%d", &v->u.number);
- return 0;
- }
- int main(int argc, char *argv[])
- {
- Vegetable v;
- double totalPrice = 0;
- //printf("\n"); // 这里还需要提示些什么,但我实在想不出该提示些什么 ^_^
- printf("蔬菜名 数量(千克)\n");
- while(1)
- {
- if(GetInput(&v))
- break;
- totalPrice += CalculatePrice(&v);
- }
- printf("需要支付:%.2lf元\n", totalPrice);
- return 0;
- }
复制代码 |
|