所以我有这个代码,用于计算总价格,然后给他们一个折扣,最后给他们提供有和没有折扣的总价格。然而,出于某种原因,我从计算中得到了非常奇怪的结果。
#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
那么我做错了什么?我试过搜索论坛,但找不到任何有助于解决我的问题的内容。任何帮助赞赏。 此外,对不起,如果这是一个非常明显的问题,但对我而言,它不是......
答案 0 :(得分:0)
您以双精度计算内容,但只能以整数精度打印。
在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);