繁体   English   中英

用 C 语言计算程序中的折扣

[英]Calculate the discount in a program in C language

我有一个给出产品总价的计划,如果购买超过 200,它应该给予 15% 的折扣。 但是在显示最终金额时,它会显示零:

#include <stdio.h>
#include <conio.h>

int main()
{
    int count;
    printf("plz enter number of product :");
    scanf("%d", &count);
    int price;
    int allprice;
    float discounted_price ;
    int i = 0;
    while(i<count)  
    {
        printf("plz enter price  %d : ",i+1);
        scanf("%d", &price);
        allprice +=price;
        i++;            
    }
    if(allprice>200)
    {
    float discount_amount = (15*allprice)/100;
    float discounted_price = (allprice-discount_amount);    
    } 

    printf("price before discount : %d ",allprice);
    printf("\n");
    printf("price after discount : %d ",discounted_price);
    return 0;
}

你有两次discounted_price

一旦你在if中计算它。
一旦外面,你output。
因此输出忽略计算值。

改变

float discounted_price = (allprice-discount_amount);

discounted_price = (allprice-discount_amount);

而且你还需要改变它的打印方式,以匹配浮点类型
(从而避免未定义的行为)。

printf("price after discount : %f ",discounted_price);

最后,如果您避免使用 integer 除法,金额会更精确:

float discount_amount = (15*allprice)/100.0;

为了更好地衡量,初始化 summation 变量(尽管并不总是看到其效果):

int allprice =0;

对于人工读取输入(即容易出现格式错误),检查scanf()的返回值并使用其他验证技术是明智的。 但这超出了您问题的答案 scope 的范围。

首先,您应该将allprice初始化为零以计算总数。 变量的初始值(如果未初始化)是未定义的。

表达方式

(15*allprice)/100; 

可能导致零,因为它正在执行 integer 分区,因为所有操作数(15,allprice,100)都是整数。 为避免这种情况,您可以将其中一个操作数转换为float ,或者在 100 之后添加 a.0 。

 (15*allprice)/100.0f; 

这应该可以解决您的问题。 让我知道它是否有帮助。

生成的代码应如下所示:

#include <stdio.h>
#include<conio.h>

int main(){
int count;
printf("plz enter number of product :");
scanf("%d", &count);
int price;
int allprice = 0;
float discounted_price ;
int i = 0;
while(i<count)  
{
    printf("plz enter price  %d : ",i+1);
    scanf("%d", &price);
    allprice +=price;
    i++;            
}
if(allprice>200)
{
float discount_amount = (15*allprice)/100.0f;
discounted_price = (allprice-discount_amount);    
} 

printf("price before discount : %d ",allprice);
printf("\n");
printf("price after discount : %f ",discounted_price);
return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM