當N件商品的成本價(CP)等於M件商品的售價(SP)時,如何使用Python計算利潤或虧損
在本文中,我們將學習一個Python程式,用於計算當N件商品的成本價(CP)等於M件商品的售價(SP)時的利潤或虧損。
假設我們已經獲得了代表N和M的值,它們分別表示N件商品的成本價等於M件商品的售價。現在我們將計算利潤或虧損百分比。
公式
profit/loss = ( (Cost Price) - (Selling Price) ) / (Selling Price) * 100
什麼是售價(SP)?
消費者購買產品或商品所支付的價格稱為售價。它高於成本價,也包含一部分利潤。
什麼是成本價(CP)?
成本價是賣家購買產品或商品的成本。之後,他會加上一部分收益或利潤。
什麼是利潤和虧損?
以高於成本價的價格出售一件商品所獲得的金額稱為利潤。
Profit = Selling Price – Cost Price.
虧損是指以低於成本價的價格出售一件商品所造成的損失。
Loss = Cost Price - Selling Price
演算法(步驟)
以下是執行所需任務應遵循的演算法/步驟:−
建立一個函式findProfitOrLoss(),透過接受n、m值作為引數來計算當CP(成本價)為'n'件商品等於SP(售價)為'm'件商品時的利潤或虧損百分比。
使用if條件語句和==運算子檢查n和m值是否相等。
如果條件為true,則列印"既無利潤也無虧損!!!"。
否則,計算利潤或虧損百分比。
建立一個變數來儲存利潤/虧損百分比的結果。
使用abs()函式(計算傳遞的數字的絕對值)將成本價和售價代入上述公式,計算利潤或虧損的值。
如果成本價大於售價,則為虧損情況,則列印虧損百分比。
否則,列印利潤百分比。
建立一個變數來儲存輸入的n值。
建立另一個變數來儲存輸入的m值。
透過向其傳遞n、m值來呼叫上面定義的findProfitOrLoss()函式,以列印利潤或虧損百分比。
示例
以下程式使用上面給出的公式根據n、m輸入值返回利潤或虧損百分比:−
# creating a function to calculate profit or loss % # when CP of 'n' items is equal to the SP of 'm' items # by accepting the n, m values as arguments def findProfitOrLoss(n, m): # checking whether the value of n, m are equal if (n == m): # printing "Neither profit nor loss!!!" if the condition is true print("Neither profit nor loss!!!") else: # variable to store profit/loss result output = 0.0 # Calculating value of profit/loss output = float(abs(n - m)) / m # checking whether n-m value value is less than 0 if (n - m < 0): # printing the loss percentage upto 4 digits after decimals print("The Loss percentage is: -", '{0:.4}' .format(output * 100), "%") else: # printing the profit percentage upto 4 digits after decimals print("The Profit percentage is: ", '{0:.6}' . format(output * 100), "%") # input n value n = 10 # input m value m = 7 # calling the above defined findProfitOrLoss() function # by passing n, m values to it to print the profit or loss percentage findProfitOrLoss(n, m)
輸出
執行上述程式後,將生成以下輸出:−
The Profit percentage is: 42.8571 %
時間複雜度 − O(1)
輔助空間 − O(1)
我們在公式中代入了數字,這樣就沒有迴圈需要遍歷,因此它只需要線性時間,即O(1)時間複雜度。
結論
在本文中,我們學習瞭如何使用Python計算當N件商品的成本價等於M件商品的售價時的利潤或虧損。此解決方案是使用線性時間複雜度方法實現的。我們還學習瞭如何使用format()函式將浮點整數格式化為n位數字。