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

เขียนโปรแกรม C หากำไรหรือขาดทุนจากการซื้อขายสินค้า


สูตรหากำไร หากราคาขายมากกว่าต้นทุน:

profit = sellingPrice - costPrice;

สูตรหาขาดทุน หากต้นทุนมากกว่าราคาขาย:

loss = costPrice - sellingPrice

นำตรรกะนี้ไปใช้ในโปรแกรมเพื่อหาว่าผู้ซื้อได้กำไรหรือขาดทุนหลังซื้อสินค้า:

ตัวอย่าง

โปรแกรม C หากำไรหรือขาดทุน:

#include <stdio.h>

int main() {
    float costPrice, sellingPrice, amount;
    
    printf("\n Enter the product cost: ");
    scanf("%f", &costPrice);
    
    printf("\n Enter the selling price: ");
    scanf("%f", &sellingPrice);
    
    if (sellingPrice > costPrice) {
        amount = sellingPrice - costPrice;
        printf("\n Profit Amount = %.4f", amount);
    } else if(costPrice > sellingPrice) {
        amount = costPrice - sellingPrice;
        printf("\n Loss Amount = %.4f", amount);
    } else {
        printf("\n No Profit No Loss!");
    }
    return 0;
}

ผลลัพธ์

เมื่อรันโปรแกรม จะได้ผลลัพธ์ดังนี้:

Enter the product cost: 450
Enter the selling price: 475.8
Profit Amount = 25.8000