Advertisement
fcamuso

Untitled

Sep 27th, 2020
438
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.70 KB | None | 0 0
  1. using System;
  2. using System.Drawing;
  3.  
  4. namespace overload_op_funzioni
  5. {
  6.   class Frazione
  7.   {
  8.     public int Num { get; set; } = 0;
  9.  
  10.     private int den;
  11.     public int Den
  12.     {
  13.       get => den;
  14.       set
  15.       {
  16.         if (value == 0) throw new ArgumentException("Denominatore zero");
  17.         den = value;
  18.       }
  19.     }
  20.     public Frazione() { }
  21.     public Frazione(int num, int den)
  22.     { Num = num; Den = den; }
  23.  
  24.     public Frazione(int n) : this(n, 1) { }
  25.     public Frazione(string s) {
  26.  
  27.       if (string.IsNullOrEmpty(s)) return;
  28.  
  29.       //if (s == null || s == "") return;
  30.  
  31.       string[] dati = s.Split('/'); //da "25ert/7" -> ["25", "7"]
  32.  
  33.       try
  34.       {
  35.         Num = int.Parse(dati[0]);
  36.       }
  37.       catch (FormatException e)
  38.       {
  39.         throw new FormatException("Stringa non nel formato 'numero/numero' o 'numero'");
  40.       }
  41.  
  42.       if (dati.Length == 1) // "25"
  43.         Den = 1;
  44.       else
  45.       {
  46.         try
  47.         {
  48.           Den = int.Parse(dati[1]);
  49.         }
  50.         catch (FormatException e)
  51.         {
  52.           throw new FormatException("Stringa non nel formato 'numero/numero' o 'numero'");
  53.         }
  54.       }
  55.     }
  56.  
  57.     public string ToString() { return $"{Num}/{Den}"; }
  58.    
  59.   }
  60.   class Program
  61.   {
  62.     static void Main(string[] args)
  63.     {
  64.       int n1 = 5, n2=7;
  65.  
  66.       int n3 = n1 + n2;
  67.  
  68.       n3++;
  69.      
  70.      
  71.       Frazione f1 = new Frazione(1,3); //  1/3
  72.       Frazione f2 = new Frazione("25/4yy");  //25/1
  73.  
  74.       //f1 += new Frazione("1/3");
  75.       //Frazione f3 = f1 + f2;
  76.  
  77.       Console.WriteLine($"{f1.ToString()} {f2.ToString()}");
  78.  
  79.       string s = null;
  80.       //Frazione f3 = new Frazione(s);
  81.  
  82.     }
  83.   }
  84. }
  85.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement