consider the code:
public double calculatePrice()
{
int discount = 0 ;
double totalPrice=itemCount*itemPrice;
double netPrice;
for(int i=0;i<NOOFITEMS.length;i++)
{
/* if(i==0)
{
if(itemCount<NOOFITEMS[i])
{ discount=0;
break;
}
}
/*if(i==NOOFITEMS.length-1)
{
if(itemCount>NOOFITEMS[i])
{ discount=50;
break;
}
}
if(itemCount<NOOFITEMS[i]&&itemCount>NOOFITEMS[i+1])
{
discount=DISCOUNTPERCENTAGE[i];
}*/
discount=10;
}
System.out.println("discount "
+discount);
System.out.println("totalprice "
+totalPrice);
netPrice=totalPrice-(totalPrice*(discount/100));
return netPrice;
}
output::
Bill ID: 501
Item NAME: grocery
NO of Item: 11
Price of Item: 250.0
discount 10
totalprice 2750.0
net price 2750.0
TRAINEE ID: 502
TRAINEE NAME: fruits
Price of Item: 300.0
Item NO: 15
discount 10
totalprice 4500.0
net price 4500.0
The value of "netprice" should be 4050 [4500-(4500*(10/100)] as per the given statement.But the value is outputed as 4500 always..
the discount/100 is not computed correctly.Always the decimal part is ignored.
Can’t figure out the error..!
The culprit is:
discountis an int, sodiscount/100is an integer division and decimals get truncated. For example,10/100is 0.To fix the issue, you can force the use of doubles: