从双变量中得到奇怪的结果 (C)

Getting odd results from double variables (C)

所以我有这段代码,用于计算总价,然后给他们折扣,最后向他们展示有折扣和没有折扣的总价。然而,出于某种原因,我从计算中得到了非常奇怪的结果。

#include <stdio.h>

int main()
{
double discountPercentage=0.0;
double numbUnits=0.0, perUnitPrice=0.0, priceWDiscount=0.0;
printf("Input # of units purchased:");
scanf("%lf", &numbUnits);

printf("Input pricer per unit:");
scanf("%lf", &perUnitPrice);

if (numbUnits*perUnitPrice >= 1000.0 && numbUnits*perUnitPrice <= 2000.0)
{
    discountPercentage = 0.10;
}
else if (numbUnits*perUnitPrice >= 2000.0 && numbUnits*perUnitPrice <= 3000.0)
{
    discountPercentage = 0.15;
}
else if (numbUnits*perUnitPrice >= 3000.0)
{
    discountPercentage = 0.20;
}
else 
{
    discountPercentage = 0.0;
}

priceWDiscount = (numbUnits*perUnitPrice) - (numbUnits*perUnitPrice*discountPercentage);
double price = numbUnits*perUnitPrice;

printf("Without discount your price would be %d.\nIncluding discount (%d) your price is %d"), price, discountPercentage, priceWDiscount;

return 0;
}

输出:

Input # of units purchased:50
Input pricer per unit:50
Without discount your price would be 266310.
Including discount (266310) your price is 2126139392

那我做错了什么?我试过搜索论坛,但找不到任何有助于解决我的问题的信息。任何帮助表示赞赏。 另外,很抱歉,如果这是一个非常明显的问题,但对我来说不是...

您正在以双精度计算内容,但仅以整数精度打印。

在您的 printf 语句中,将所有 %d 更改为 %lf

您还过早地用括号关闭了 printf 语句。您需要将它移到分号之前的末尾,以便 printf 实际上知道它应该打印哪些变量。

所以你总共需要改变这个:

printf("Without discount your price would be %d.\nIncluding discount (%d) your price is %d"), price, discountPercentage, priceWDiscount;

为此:

printf("Without discount your price would be %lf.\nIncluding discount (%lf) your price is %lf", price, discountPercentage, priceWDiscount);