在C#编程中,如何将某一实数值以分数的形式表达
1个回答
展开全部
using System;
using System.Collections.Generic;
using System.Linq;
namespace MyApplication
{
/// <summary>
/// 用分数形式表示实数类
/// </summary>
public class RealValue
{
private int denominator;
private int numerator;
/// <summary>
/// 构造函数
/// </summary>
public RealValue()
{
Denominator = 1;
Numerator = 0;
}
/// <summary>
/// 构造函数
/// </summary>
/// <param name="numerator">分子</param>
/// <param name="denominator">分母</param>
public RealValue(int numerator, int denominator)
{
Denominator = denominator;
Numerator = numerator;
}
/// <summary>
/// 获取或设置分母
/// </summary>
public int Denominator
{
get { return denominator; }
set
{
if (value == 0)
{
throw new ArgumentException("分母不能为零!");
}
denominator = value;
}
}
/// <summary>
/// 获取或设置分子
/// </summary>
public int Numerator
{
get { return numerator; }
set { numerator = value; }
}
/// <summary>
/// 获取实数值
/// </summary>
public float Value
{
get { return (float)numerator / (float)denominator; }
}
}
class Program
{
/// <summary>
/// 测试
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
RealValue r1 = new RealValue(1, 3);
Console.WriteLine("分数={0}/{1};值={2}",
r1.Numerator,
r1.Denominator,
r1.Value);
RealValue r2 = new RealValue(4, 5);
Console.WriteLine("分数={0}/{1};值={2}",
r2.Numerator,
r2.Denominator,
r2.Value);
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询