这是我的作业
我想写出方法卖出,允许股票的某些股票以给定价格出售。该方法有两个参数:作为int的多个份额,以及作为double的每股价格。该方法返回一个布尔值,以指示销售是否成功。例如:
// myStock now has 30 shares at total cost $90.00
boolean success = myStock.sell(5, 4.00);
// sells 5 shares at $4.00 successfully
// myStock now has 25 shares at total cost $70.00
success = myStock.sell(2, 5.00);
// sells 2 shares at $5.00 successfully
// myStock now has 23 shares at total cost $60.00
My Code :
public static void buy(int numBuyShares, double priceBuyShares)
{
double tempTotalCost = ((double)numBuyShares * priceBuyShares);
totalShares += numBuyShares;
totalCost += priceBuyShares;
}
public static void sell(int numSellShares, double priceSellShares)
{
?????
}
1.。)如何使用之前的购买股票和成本来减去卖出的股票和价格?
答案 0 :(得分:0)
我想你想要这样的东西......
public static boolean sell(int numSellShares, double priceSellShares) {
double sellCost = numSellShares * priceSellShares; // calculate total $
// to sell
// assure 2 things:
// shares to sell does not exceed total # of shares; and
// total $ to sell does not exceed total cost
if (numSellShares <= totalShares && sellCost <= totalCost) {
// subtract #shares and cost from total
totalShares -= numSellShares;
totalCost -= sellCost;
return true; // return success
}
// tried to sell more shares or $ than what exists
else {
return false; // return failure
}
}
但又一次,不知道你的要求是什么,所以不能肯定是什么决定成败。