[英]A C program where a discount is applied on the cheaper item
该程序有些工作,但我不知道如何使它将折扣金额添加到正确的项目中,基本上程序如何判断哪个项目更便宜,对该项目应用折扣,然后将其添加到另一个不是的项目打折(它是全价,因为它比其他商品贵)
#include "stdio.h"
// a program that takes the price of two items, applies a discount on the cheaper item and then calculates the outcome that needs to be paid.
int main()
{
float item_one;
float item_two;
float discount_percentage= 50;
float discount_amount;
float total;
float cheaper_item;
printf("\n Insert the price of the first item : ");
scanf("%f", &item_one);
printf("\n Insert the price of the first item : ");
scanf("%f", &item_two);
if ( item_one < item_two)
cheaper_item = item_one;
else
cheaper_item = item_two;
discount_amount = (discount_percentage*cheaper_item)/100;
printf ("\n Discount amount : %f \n", discount_amount);
total = (discount_amount + cheaper_item);
printf ("Total to pay : %f \n", total);
}
是总数的计算是错误的。 添加两个价格减去折扣:
total = (item_one + item_two - discount_amount);
开始编程时的“goto”解决方案是“使用更多变量和更多代码”试图解决问题。 这会导致混乱。
以下仅使用 3 个float
s(应该使用double
s),并且使用更少的行实现比 OP 略多。
请注意,变量是在需要它们的位置/时间附近声明的。 在这个有限的应用中, discount
有两个目的:初始利率,然后是(假定的)美元金额。
很明显,折扣是从“便宜商品”的价格计算出来的,然后从总成本中减去。
#include "stdio.h"
int main()
{
float item_one;
printf("\n Insert the price of the first item : ");
scanf("%f", &item_one);
float item_two;
printf("\n Insert the price of the second item : "); // Typo
scanf("%f", &item_two);
float discount = 0.50; // == 50%
if (item_one < item_two)
discount *= item_one; // discount now $
else
discount *= item_two; // discount now $
char *fmt = "%20s: %8.2f\n";
printf (fmt, "Total Price", item_one + item_two);
printf (fmt, "Discount amount", discount);
printf (fmt, "Total cost", item_one + item_two - discount);
}
Output
Insert the price of the first item : 100.00
Insert the price of the second item : 20.00
Total Price: 120.00
Discount amount: 10.00
Total cost: 110.00
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.