Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

หาต้นทุน (Cost Price) จากราคาขายและเปอร์เซ็นต์กำไร/ขาดทุนใน C++

กำหนดราคาขาย (Selling Price) และเปอร์เซ็นต์กำไรหรือขาดทุน หาต้นทุน (Cost Price)

สูตร

กรณีกำไร: Cost Price = (Sell Price × 100) / (100 + %Profit)

กรณีขาดทุน: Cost Price = (Sell Price × 100) / (100 - %Loss)

ตัวอย่างโค้ด

#include <iostream>
using namespace std;

float priceWhenProfit(int sellPrice, int profit) {
    return (sellPrice * 100.0) / (100 + profit);
}

float priceWhenLoss(int sellPrice, int loss) {
    return (sellPrice * 100.0) / (100 - loss);
}

int main() {
    int SP, profit, loss;

    SP = 1020; profit = 20;
    cout << "Cost Price When Profit: " << priceWhenProfit(SP, profit) << endl;

    SP = 900; loss = 10;
    cout << "Cost Price When Loss: " << priceWhenLoss(SP, loss) << endl;

    return 0;
}

ผลลัพธ์

Cost Price When Profit: 850
Cost Price When Loss: 1000

การตรวจสอบ

  • กำไร 20%: ต้นทุน 850 × 1.20 = 1020 ✓
  • ขาดทุน 10%: ต้นทุน 1000 × 0.90 = 900 ✓