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

โปรแกรม C++ ตรวจสอบถังน้ำจะล้น ว่าง หรือเต็มพอดีในเวลาที่กำหนด


บทนำ

กำหนดอัตราการเติมน้ำ ความสูงและรัศมีของถัง ต้องการตรวจสอบว่าถังจะล้น (overflow), ว่าง (underflow) หรือเต็มพอดี (filled) ในเวลาที่กำหนด

ตัวอย่าง

  • radius=2, height=5, rate=10 → tank overflow
  • radius=5, height=10, rate=10 → tank underflow

แนวคิด

  1. คำนวณปริมาตรถังเพื่อหาอัตราการไหลจริง
  2. เปรียบเทียบเวลาที่คาดหวัง (expected) กับเวลาจริง (original):
    • expected < original → overflow
    • expected > original → underflow
    • expected = original → filled

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

#include <bits/stdc++.h>
using namespace std;

float volume(int rad, int height) {
    return ((22.0 / 7) * rad * rad * height);  // สูตรปริมาตรทรงกระบอก: πr²h
}

void check(float expected, float original) {
    if (expected < original)
        cout << "tank overflow";
    else if (expected > original)
        cout << "tank underflow";
    else
        cout << "tank filled";
}

int main() {
    int rad = 2, height = 5, rate = 10;
    float original = 70.0;
    float expected = volume(rad, height) / rate;
    check(expected, original);
    return 0;
}

ผลลัพธ์

tank overflow