C# 練習題 (5)

C# 練習題 (5)

練習題 (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 並處理它。

程式碼:

  1. using System;
  2. namespace ReynoldsNumber
  3. {
  4. public class Program
  5. {
  6. public static void readValue( string name, out double od)
  7. {
  8. string s = "";
  9. Console.Write ( "Please input {0}: ", name);
  10. s = Console.ReadLine ( );
  11. while ( double.TryParse (s, out od) == false )
  12. {
  13. Console.Write ( "Please input {0}: ", name);
  14. s = Console.ReadLine ( );
  15. }
  16. }
  17. public static void Main( string [ ] args)
  18. {
  19. double d = 0.0, v = 0.0, rho = 0.0, mu = 0.0, reynolds = 0.0;
  20. string ynFlag = "";
  21. do
  22. {
  23. readValue( "diameter", out d);
  24. readValue( "velocity", out v);
  25. readValue( "density", out rho);
  26. readValue( "viscosity ", out mu);
  27. try
  28. {
  29. reynolds = (d*v*rho)/mu;
  30. }
  31. catch (DivideByZeroException dbze)
  32. {
  33. Console.WriteLine (dbze.Message );
  34. }
  35. if (reynolds < 2100 )
  36. {
  37. Console.WriteLine ( "Laminar flow" );
  38. }
  39. else if ( (reynolds >= 2100 ) && (reynolds < 4000 ) )
  40. {
  41. Console.WriteLine ( "Transient flow" );
  42. }
  43. else
  44. {
  45. Console.WriteLine ( "Turbulent Flow" );
  46. }
  47. Console.Write ( "Do you want to calculate again (y/n)? " );
  48. ynFlag = Console.ReadLine ( );
  49. } while ( String.Compare (ynFlag, "y", true ) == 0 );
  50. }
  51. }
  52. }