練習題 (5):Modify the above program such that it will ask for 'Do you want to calculate again (y/n), if you say 'y', it'll again ask the parameters. If 'n', it'll exit. (Do while loop )
While running the program give value mu = 0. See what happens. Does it give 'DIVIDE BY ZERO' error? Does it give 'Segmentation fault..core dump?'. How to handle this situation. Is there something built in the language itself? (Exception Handling )
跟 (4) 一樣的題目,只是加上 do while 迴圈,來讀取使用者是否繼續計算 Reynolds number。並且練習如何利用 try catch 來補抓 DivideByZeroException 並處理它。
程式碼:
-
using System;
-
namespace ReynoldsNumber
-
{
-
public class Program
-
{
-
public static void readValue( string name, out double od)
-
{
-
string s = "";
-
Console.Write ( "Please input {0}: ", name);
-
s = Console.ReadLine ( );
-
while ( double.TryParse (s, out od) == false )
-
{
-
Console.Write ( "Please input {0}: ", name);
-
s = Console.ReadLine ( );
-
}
-
}
-
public static void Main( string [ ] args)
-
{
-
double d = 0.0, v = 0.0, rho = 0.0, mu = 0.0, reynolds = 0.0;
-
string ynFlag = "";
-
do
-
{
-
readValue( "diameter", out d);
-
readValue( "velocity", out v);
-
readValue( "density", out rho);
-
readValue( "viscosity ", out mu);
-
try
-
{
-
reynolds = (d*v*rho)/mu;
-
}
-
catch (DivideByZeroException dbze)
-
{
-
Console.WriteLine (dbze.Message );
-
}
-
if (reynolds < 2100 )
-
{
-
Console.WriteLine ( "Laminar flow" );
-
}
-
else if ( (reynolds >= 2100 ) && (reynolds < 4000 ) )
-
{
-
Console.WriteLine ( "Transient flow" );
-
}
-
else
-
{
-
Console.WriteLine ( "Turbulent Flow" );
-
}
-
Console.Write ( "Do you want to calculate again (y/n)? " );
-
ynFlag = Console.ReadLine ( );
-
} while ( String.Compare (ynFlag, "y", true ) == 0 );
-
}
-
}
-
}
|