----------------------------------------------------------------------Currency.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication4
{
//类和结构相似
public struct Currency
{
private uint dollars; //元
private ushort cents; //分
public Currency(uint i, ushort s)//初始化构造函数
{
this.dollars = i;
this.cents = s;
}
public override string ToString()
{
return string.Format("{0}.{1,2:00}", dollars, cents);
}
//看情况选择是显示装换还是隐式转换,(uint和ushort都可以隐式转换为float)
//重载运算符必须使用public static
//implicit 隐式转换
//把Currency对象隐式转换为float类型
public static implicit operator float(Currency c)
{
return c.dollars + c.cents / 100.0f;
}
//explicit为显式转换
//把float对象显式转换为Currency类型
public static explicit operator Currency(float f)
{
checked//溢出则抛出异常
{
uint i = (uint)f;
ushort s = Convert.ToUInt16((f - i) * 100);
return new Currency(i, s);
}
}
}
}
----------------------------------------------------------------------主程序
Currency c = new Currency(50, 35);
float f = (float)(c);
c = (Currency)f;
Console.WriteLine(c.ToString());
Console.ReadKey();
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。