I'm having trouble getting total to solve properly. Something seems to be messing up the value of price after it leaves the switch structure. Please forgive all the test code.
Code:
#include <stdio.h>
int main()
{
int sentinel = 0, product = 0, quantity;
float total = 0, price = 0;
while (sentinel != 1)
{
printf("Enter product number or 6 to exit: ");
scanf("%d", &product);
switch (product)
{
case 1:
price = 2.98;
/* ---------Test code----------- */
printf("price: %.2f\n", price);
printf("product: %d\n", product);
/* ---------End of test-----------*/
break;
case 2:
price = 4.50;
break;
case 3:
price = 9.98;
break;
case 4:
price = 4.49;
break;
case 5:
price = 6.87;
break;
case 6:
sentinel = 1;
price = 0;
break;
default:
printf("Enter 1 through 6 only\n");
break;
}
/* -----------test code------------------------------------------------ */
printf("-----values after switch-----\n");
printf("%price: .2f\n", price);
printf("product: %d\n", product);
/* ----------------End of test ----------------------------------*/
total = ( float ) quantity * price + total;
if (product >= 6)
break;
/* Moved to bottom so you can exit without this interfering */
printf("Enter quantity: ");
scanf("%d", &quantity);
/* -----------------test code----------------- */
printf("quantity: %d\n", quantity);
/* -----------------End of test--------------- */
}
printf("The total value is: %.2f\n", total);
/* -----------------test code----------------- */
printf("quantity: %d", quantity);
printf("\nprice: %.2f\n", price);
/* end of test code */
return 0;
}
It's been a while since I've last picked up my C book at least half a year or so. I'm thinking maybe it's something I've forgotten, but I could have sworn C doesn't use local and global variables.