ตัวอย่างโค้ดภาษาซี ในการคำนวณหาจำนวนเงิน 1000, 500, 100, 50, 20, 10, 5, 2, 1 บาท และเหรียญ 50, 25 สตางค์ ซึ่งได้เป็นการปรับปรุงโค้ดจากบทความ “โค้ดภาษาซี คำนวณการแยก/แลกเปลี่ยนเงินของจำนวนเงิน 1000, 500, 100, 50, 20, 10, 5, 2, 1 บาท” ให้รองรับการคำนวณสตางค์
ตัวอย่างเช่น กรอกจำนวนเงิน 9888.88 บาท โปรแกรมจะทำการคำนวณหาจำนวนเงินที่ได้แต่ละชนิดดังนี้
1000 บาท = 9
500 บาท = 1
100 บาท = 3
50 บาท = 1
20 บาท = 1
10 บาท = 1
5 บาท = 1
2 บาท = 1
1 บาท = 1
50 สตางค์ = 1
25 สตางค์ = 1
1 สตางค์ = 13 (ไม่สามารถเปลี่ยนได้)
ตัวอย่าง Flowchart

ตัวอย่างโค้ด
/***************************************************
* Author : CS Developers
* Author URI: https://www.comscidev.com
* Facebook : https://www.facebook.com/CSDevelopers
***************************************************/
#include<stdio.h>
int main()
{
float money;
int money_baht;
float money_satang;
printf("Enter money for change : ");
scanf("%f", &money);
money_baht = (int)money;
money_satang = money - money_baht;
if(money_baht >= 1000){
printf("\n 1000 Baht = %d ", money_baht/1000);
money_baht = money_baht % 1000;
}
if(money_baht >= 500){
printf("\n 500 Baht = %d", money_baht/500);
money_baht = money_baht % 500;
}
if(money_baht >= 100){
printf("\n 100 Baht = %d", money_baht/100);
money_baht = money_baht % 100;
}
if(money_baht >= 50){
printf("\n 50 Baht = %d", money_baht/50);
money_baht = money_baht % 50;
}
if(money_baht >= 20){
printf("\n 20 Baht = %d", money_baht/20);
money_baht = money_baht % 20;
}
if(money_baht >= 10){
printf("\n 10 Baht = %d", money_baht/10);
money_baht = money_baht % 10;
}
if(money_baht >= 5){
printf("\n 5 Baht = %d", money_baht/5);
money_baht = money_baht % 5;
}
if(money_baht >= 2){
printf("\n 2 Baht = %d", money_baht/2);
money_baht = money_baht % 2;
}
if(money_baht >= 1){
printf("\n 1 Baht = %d", money_baht);
}
if(money_satang >= 0.50)
{
printf("\n 50 Satang = %d", (int)(money_satang / 0.50));
money_satang = money_satang - 0.50;
}
if(money_satang >= 0.25)
{
printf("\n 25 Satang = %d", (int)(money_satang / 0.25));
money_satang = money_satang - 0.25;
}
if(money_satang >= 0.01)
{
printf("\n 1 Satang = %.0f (can't change) ", (money_satang * 100));
}
return 0;
}
อธิบายเพิ่มเติม
- ตัวแปร
money
ใช้เก็บจำนวนเงินที่กรอกเข้ามาในโปรแกรม โดยกำหนดเป็นชนิดfloat
เพื่อให้รองรับทศนิยม - ตัวแปร
money_baht
ใช้เก็บจำนวนเงินที่เป็นจำนวนเต็ม โดยกำหนดเป็นชนิดint
ซึ่งจะได้ค่าจากนำตัวแปรmoney
แปลงเป็นชนิดint
(โค้ดบรรทัดที่ 18) - ตัวแปร
money_satang
ใช้เก็บจำนวนเงินที่เป็นสตางค์ โดยกำหนดเป็นชนิดfloat
ซึ่งจะได้ค่าจากนำตัวแปรmoney
ลบด้วยตัวแปรmoney_baht
(โค้ดบรรทัดที่ 19) money_satang * 100
คือ การนำสตางค์คงเหลือที่ไม่สามารถเปลี่ยนได้ มาทำให้อยู่ในรูปจำนานเต็ม%.0f
ให้แสดงค่าชนิดfloat
แบบไม่ต้องแสดงทศนิยม
ผลลัพธ์
