如果允许用户在购物车中添加其他商品,我该怎么做才能计算出用户购买的商品的总价? chosen1
的值是否会更改,还是仅添加新项而不删除chosen1
中存储的先前值?我必须在这里使用数组吗?我刚刚开始学习此方法,一切令人困惑; <
#include <stdio.h>
#include <stdlib.h>
char chosen1;
int Qty1;
printf("Pick your items:\n");
printf("a-Onions\nb-Leek\nc-Pak Choy\nd-Bell Peppers\ne-Celery\nf-Chicken breast\ng-Chicken thigh\nh-Salmon\ni-Meat\nj-Garlic\n");
do
{
printf("Item?\n");
scanf(" %c",&chosen1);
}
while ((chosen1 != 'a')&&(chosen1!='b')&&(chosen1!='c')&&(chosen1!='d')&&(chosen1!='e')&&
(chosen1!='f')&&(chosen1!='g')&&(chosen1!='h')&&(chosen1!='i')&&(chosen1!='j'));
printf("Quantity?\n");
scanf("%d",&Qty1);
printf("Item:%c||Qty:%d\n",chosen1,Qty1);
printf("Add another item?");
char
和int
之类的变量在每个时刻只能存储一个值。您不需要此任务的数组。为了计算总价,您可以定义float
类型的变量(用于带点的数字),并使用运算符switch
为每个项目添加适当的金额:
float totalPrice = 0;
...
float costOfItem;
switch (chosen1) // we going to appropriate "case" depending on value of chosen1
{
case 'a': costOfItem = 10.5; break; // here must be cost of onions
case 'b': costOfItem = 4.0; break; // here must be cost of leek, etc
...
}
totalPrice += costOfItem * Qty1; // here we take the sum of left and right parts of operator "+=" and put it in the left part, i.e. in variable totalPrice