2017-08-14 80 views
-5

我的家庭作業是:我經營一家巴士公司,根據巴士座位數和乘客人數,我需要知道需要使用多少巴士。例如:如果我有17名乘客和3個座位的巴士,我必須使用6輛巴士。前15名乘坐5輛巴士,剩下2輛巴士。巴士公司只使用算法

我不能使用for循環,if語句或遞歸,只能算術。

這是我的僞代碼,但它是錯誤的:

numbus=numOfPeople/seat; 
    remain=numOfPeople % seat; 
    temp=numOfBus % remain; 
    orderBus=numbus+temp; 
    System.out.println(orderbus); 
+0

你能比「這是錯的」更具體? – EJoshuaS

+0

line'temp = numOfBus%remain;'沒有任何意義,您應該使用'Math.ceil((double)numOfPeople/seat)'來計算總線數量 –

+0

什麼是'numOfBus'?在問題的範圍內沒有定義。你可能是指第一行定義的'numbus'? –

回答

0

的錯誤是:爲了計算保留:

remain = numOfPeople % numbus 

最後:

orderBus = numbus + (remain > 0 ? 1 : 0) // an additional bus if the remain > 0 

完整代碼:

numbus = numOfPeople/seat; 
remain = numOfPeople % numbus; 
orderBus = numbus + (remain > 0 ? 1 : 0); 
// in case you can't use ternary form: 
// orderBus = numbus + (remain^0) 
System.out.println(orderbus); 
+0

我不同意這一點。如果我們有5人,並且有3人的公共汽車,您的解決方案表示我們需要訂購3輛公共汽車。 (1滿+(餘數2))。 –

+0

@MattClark你是對的!固定,謝謝。 – alfasin

+0

我打算用ternary發佈一個解決方案,但是這是否可以作爲OP聲明他不能使用的if語句? –

0

由於您對無循環和ifs有嚴格要求,因此您可能也不能使用三元運算符。事實上,你不需要那些。

它可以是簡單的:

System.out.println(Math.ceil(passengers/seat)); 

例如(Math.ceil(17/3.0));給你6.0。你需要的是通過將乘客座位得到商。如果商不是一個整數,總是將它四捨五入。這通過使用Math.ceil()來實現。

因此,如果有餘,你湊夠1(1輛更多公共汽車渡輪乘客的其餘部分)

+0

OP在評論中寫道,他不能使用數學LIB – alfasin