Mass of a prism using a 'While loop'
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/189409/image.png)
6 个评论
回答(1 个)
I copied the solution I wrote as a comment here as an answer:
First of all, your calculation is wrong: mass = density * volume
As far as I understood the question, you should calculate the mass of a rectangular prism with a hole (cylinder) in it. To get the total mass you have to subtract the mass of the hole from the mass of the massive rectangular prism.
Although I have to admit, that the given task is very bad! It mixes diameter and radius of a hole/cylinder and the parameter for the height of the rectangular prism is missing.
If I assume, that it's the diameter, that is meant by "(r=0.05:0.1:<W/2)" and not the radius, and height = width (quadratic) for the prism, than the following code should do the trick:
% mass of rectangular prism with a hole (cylinder) in it clear, clc rho = 2700;
W = 1; % Width of rectangular prism L = 2; % Length of rectangular prism d0 = 0.05; % Initial diameter of the hole (cylinder) dStepwidth = 0.1; % Stepwidth of the diameter of the hole dMax = W/2; % Maximum diameter of the hole
for d = d0 : dStepwidth : dMax mass_prism = W^2 * L * rho; mass_hole = (pi * (d/2).^2 * L) * rho; mass_total = mass_prism - mass_hole; printf ( 'd = %0.3f m \nW = %0.1f m \nL = %0.1f m \nRho = %0.3f kg/m^3 \nm = %0.5f kg\n\n',... d, W, L, rho, mass_total); end
Converting a for-loop into a while-loop is simple, you just do, what the for-loop does by hand:
1. create a variable d outside of the loop and initialize it with the starting value d0
2. think about the condition, when the while-loop should stop or continue to run. In your case this is d <= dMax. The loop continues as long as d is lower or equal dMax.
3. Increase variable d by your stepwidth dStepwidth inside the loop every iteration (I assume you forgot that step, when the loop doesn't end in your case).
d = d + dStepwidth;
Here is the while-loop version:
% mass of rectangular prism with a hole (cylinder) in it clear, clc rho = 2700;
W = 1; % Width of rectangular prism L = 2; % Length of rectangular prism d0 = 0.05; % Initial diameter of the hole (cylinder) dStepwidth = 0.1; % Stepwidth of the diameter of the hole dMax = W/2; % Maximum diameter of the hole
d = d0; % changing diameter while d <= dMax mass_prism = W^2 * L * rho; mass_hole = (pi * (d/2).^2 * L) * rho; mass_total = mass_prism - mass_hole; fprintf ( 'd = %0.3f m \nW = %0.1f m \nL = %0.1f m \nRho = %0.3f kg/m^3 \nm = %0.5f kg\n\n',... d, W, L, rho, mass_total); d = d + dStepwidth; end
0 个评论
另请参阅
类别
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!