C++ 程式:檢查當 n 個實心球浸入水箱時水箱是否溢位


給定圓柱形水箱的半徑和高度、'n' 個球形實心球的半徑以及水箱中水的體積,任務是檢查當球浸入水箱時水箱是否會溢位。

計算體積的公式

圓柱體 

3.14 * r * r * h

其中,r 是水箱的半徑,h 是水箱的高度

球體 

(4/3) * 3.14 * R * R * R

其中,R 是球體半徑

輸入 

tank_height = 5
tank_radius = 2
water_volume = 10
capacity = 10
ball_radius = 2

輸出 

It will overflow

下面使用的方案如下

  • 輸入給定的尺寸,如水箱半徑、水箱高度、要浸入的球數和球體半徑

  • 透過應用公式計算水箱的容量(體積)

  • 透過應用公式計算球體的體積

  • 計算水的體積,因為每當球浸入水箱時,水的體積都會增加。

  • 透過將水的體積和球體的體積相加來計算總體積

  • 檢查條件以確定水箱是否會溢位

    • 如果總體積大於容量,則水箱會溢位

    • 如果總體積小於容量,則水箱不會溢位

演算法

Step 1→ declare function to check whether tank will overflow or not
   void overflow(int H, int r, int h, int N, int R)
      declare float tank_cap = 3.14 * r * r * H
      declare float water_vol = 3.14 * r * r * h
      declare float balls_vol = N * (4 / 3) * 3.14 * R * R * R
      declare float vol = water_vol + balls_vol
      IF (vol > tank_cap)
         Print it will overflow
      End
      Else
         Print No it will not overflow
      End
Step 2→ In main()
   Declare int tank_height = 5, tank_radius = 2, water_volume = 10,
   capacity = 10, ball_radius = 2
   call overflow(tank_height, tank_radius, water_volume, capacity, ball_radius)

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
//check whether tank will overflow or not
void overflow(int H, int r, int h, int N, int R){
   float tank_cap = 3.14 * r * r * H;
   float water_vol = 3.14 * r * r * h;
   float balls_vol = N * (4 / 3) * 3.14 * R * R * R;
   float vol = water_vol + balls_vol;
   if (vol > tank_cap){
      cout<<"it will overflow";
   }
   else{
      cout<<"No it will not overflow";
   }
}
int main(){
   int tank_height = 5, tank_radius = 2, water_volume = 10, capacity = 10, ball_radius = 2;
   overflow(tank_height, tank_radius, water_volume, capacity, ball_radius);
   return 0;
}

輸出

如果執行上述程式碼,它將生成以下輸出:

it will overflow

更新於: 2020-08-13

194 次檢視

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告