fork(12) download
  1. using System;
  2.  
  3. public class Test
  4. {
  5. public static void Main()
  6. {
  7. Console.WriteLine(FractionToDouble("4 1/5"));
  8. }
  9.  
  10. private static double FractionToDouble(string fraction) {
  11. double result;
  12.  
  13. if(double.TryParse(fraction, out result)) {
  14. return result;
  15. }
  16.  
  17. string[] split = fraction.Split(new char[] { ' ', '/' });
  18.  
  19. if(split.Length == 2 || split.Length == 3) {
  20. int a, b;
  21.  
  22. if(int.TryParse(split[0], out a) && int.TryParse(split[1], out b)) {
  23. if(split.Length == 2) {
  24. return (double)a / b;
  25. }
  26.  
  27. int c;
  28.  
  29. if(int.TryParse(split[2], out c)) {
  30. return a + (double)b / c;
  31. }
  32. }
  33. }
  34.  
  35. throw new FormatException("Not a valid fraction.");
  36. }
  37. }
Success #stdin #stdout 0.03s 33944KB
stdin
Standard input is empty
stdout
4.2