In: Computer Science
In class need to define two fields:
1. Integer part of the number - ulong; & fractional part of the number - ushort in C#
Using C#, create the following methods:
1. Method for adding two prices (parameters for function is 2 numbers, integer(main currency) and fractional parts(Fractional currency))
2. Method for adding two prices(parameter is object of same type as your class)
3. Method for adding two prices(parameter is string)
Code:
using System;
class Amount
{
private ulong integerPart;
private ushort fractionPart;
public Amount(ulong integerPart, ushort
fractionPart)
{
this.integerPart =
(ulong) integerPart + (ulong) fractionPart / 100;
this.fractionPart =
(ushort) (fractionPart % 100);
}
public void AddPrices(ulong integerPart,
ushort fractionPart)
{
this.integerPart +=
(ulong) integerPart + (ulong) ((this.fractionPart + fractionPart) /
100);
this.fractionPart =
(ushort) ((this.fractionPart + fractionPart) % 100);
}
public void AddPrices(Amount c)
{
AddPrices(c.integerPart,
c.fractionPart);
}
public void AddPrices(string s)
{
string[] money =
s.Split('.');
ulong integerPart =
Convert.ToUInt64(money[0]);
ushort fractionPart =
Convert.ToUInt16(money[1]);
AddPrices(new
Amount(integerPart, fractionPart));
}
public override string ToString()
{
return $"Amount:
${this.integerPart}.{this.fractionPart}";
}
}
class Program
{
static void Main(string[] args)
{
//
Console.WriteLine("Hello World!");
Amount a = new
Amount(20, 98);
Amount b = new
Amount(23, 88);
Console.WriteLine(a.ToString());
a.AddPrices(20,
50);
Console.WriteLine(a.ToString());
a.AddPrices(b);
Console.WriteLine(a.ToString());
a.AddPrices("10.87");
Console.WriteLine(a.ToString());
}
}
Output:
Code screenshots: