Hi I came across a nice use for conditional operator. I always hated dealing text for "You have 1 units" or "You have 2 units" - ie, dealing with plural for single items.
Code:
int main(void)
{
const double unit_price = 3.50; /* unit price in euro */
const double discount1 = 0.05; /* discount for more than 10 */
const double discount2 = 0.10; /* discount for more than 20 */
const double discount3 = 0.15; /* discount for more than 50 */
double total_price = 0.0;
int quantity = 0;
printf("\nWelcome to the shop. Basic unit costs %.2f. Discounts available.",unit_price);
printf("\n5%% off on more than 10. 10%% off on more than 20. 15%% off on more than 50!");
printf("\nEnter the number of units you want to buy: ");
scanf("%d",&quantity);
total_price = quantity*unit_price*(1.0 -
(quantity>50 ? discount3 : (
quantity>20 ? discount2 : (
quantity>10 ? discount1 : 0.0))));
printf("The price for %d unit%s is %.2f euro.\n", quantity, quantity>1 ? "s" : "", total_price);
/* quantity>1 check shows how to deal single or plural units */
return 0;
}
The code segment:
Code:
quantity, quantity>1 ? "s" : ""
is pretty cool. It's one in my bookmarks. I love that! Going back I always neglected the shorthand conditional op.
Welcome to the shop. Basic unit costs 3.50. Discounts available.
5% off on more than 10. 10% off on more than 20. 15% off on more than 50!
Enter the number of units you want to buy: 1
The price for 1 unit is 3.50 euro.