2016-04-22 23 views
0

我很感谢这个帮助。方法不正确计算和显示值?

例如,我的代码是;

class Candy extends DessertItem 
{ 
double weight; 
double price; 
Candy(String n, double w, double p) 
{ 
super(n); 
weight = w; 
price = p; 
} 
public double getCost() 
{ 
double cost = weight*price; 
int costinCents = (int)cost*100; 
cost = costinCents /100.0; 
return cost; 
} 
public String toString() 
{ 
return name+"\t\t\t\t$" + getCost() + "\n\t" + weight + " lbs @ $" + price; 
} 
} 

,输出是:

Peanut Butter Fudge    $8.0 
    2.25 lbs @ $3.99 

为什么显示$ 8.0,而不是$ 8.97?

任何帮助,将不胜感激!谢谢。

+1

你认为'(int)cost * 100是什么意思? – Savior

+0

哎呀,我的错。我如何让它只显示2个小数点? – emansour619

+1

http://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-in-java – Savior

回答

0

尝试int costinCents = (int) (cost*100)

具体的例子: 成本= 3.5 ==>(int)的成本* 100 = 300

成本= 3.5 ==>(int)的(成本* 100)= 350

+0

明白了。我如何得到8.97美元而不是8.977500000000001美元? 我尝试使用上述链接与.2%,它没有工作,因为我使用的是返回,而不是system.out。 – emansour619

+0

请参考: http://stackoverflow.com/questions/2538787/how-to-display-an-output-of-float-data-with-2-decimal-places-in-java –

+0

我看到,但我如何将它解释为我的回报声明? return name +“\ t \ t \ t \ t $”+ getCost()+“\ n \ t”+ weight +“lbs @ $”+ price; – emansour619