- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我想在 C# 中将 double 值显示为分数,我该怎么做?
谢谢
最佳答案
试试这个用于 C# 的 Fraction 类。
/*
* Author: Syed Mehroz Alam
* Email: smehrozalam@yahoo.com
* URL: Programming Home "http://www.geocities.com/smehrozalam/"
* Date: 6/15/2004
* Time: 10:54 AM
*
*/
using System;
namespace Mehroz
{
/// <summary>
/// Classes Contained:
/// Fraction
/// FractionException
/// </summary>
/// Class name: Fraction
/// Developed by: Syed Mehroz Alam
/// Email: smehrozalam@yahoo.com
/// URL: Programming Home "http://www.geocities.com/smehrozalam/"
/// Version: 2.0
///
/// What's new in version 2.0:
/// * Changed Numerator and Denominator from Int32(integer) to Int64(long) for increased range
/// * renamed ConvertToString() to (overloaded) ToString()
/// * added the capability of detecting/raising overflow exceptions
/// * Fixed the bug that very small numbers e.g. 0.00000001 could not be converted to fraction
/// * Other minor bugs fixed
///
/// What's new in version 2.1
/// * overloaded user-defined conversions to/from Fractions
///
///
/// Properties:
/// Numerator: Set/Get value for Numerator
/// Denominator: Set/Get value for Numerator
/// Value: Set an integer value for the fraction
///
/// Constructors:
/// no arguments: initializes fraction as 0/1
/// (Numerator, Denominator): initializes fraction with the given numerator and denominator values
/// (integer): initializes fraction with the given integer value
/// (long): initializes fraction with the given long value
/// (double): initializes fraction with the given double value
/// (string): initializes fraction with the given string value
/// the string can be an in the form of and integer, double or fraction.
/// e.g it can be like "123" or "123.321" or "123/456"
///
/// Public Methods (Description is given with respective methods' definitions)
/// (override) string ToString(Fraction)
/// Fraction ToFraction(string)
/// Fraction ToFraction(double)
/// double ToDouble(Fraction)
/// Fraction Duplicate()
/// Fraction Inverse(integer)
/// Fraction Inverse(Fraction)
/// ReduceFraction(Fraction)
/// Equals(object)
/// GetHashCode()
///
/// Private Methods (Description is given with respective methods' definitions)
/// Initialize(Numerator, Denominator)
/// Fraction Negate(Fraction)
/// Fraction Add(Fraction1, Fraction2)
///
/// Overloaded Operators (overloaded for Fractions, Integers and Doubles)
/// Unary: -
/// Binary: +,-,*,/
/// Relational and Logical Operators: ==,!=,<,>,<=,>=
///
/// Overloaded user-defined conversions
/// Implicit: From double/long/string to Fraction
/// Explicit: From Fraction to double/string
/// </summary>
public class Fraction
{
/// <summary>
/// Class attributes/members
/// </summary>
long m_iNumerator;
long m_iDenominator;
/// <summary>
/// Constructors
/// </summary>
public Fraction()
{
Initialize(0,1);
}
public Fraction(long iWholeNumber)
{
Initialize(iWholeNumber, 1);
}
public Fraction(double dDecimalValue)
{
Fraction temp=ToFraction(dDecimalValue);
Initialize(temp.Numerator, temp.Denominator);
}
public Fraction(string strValue)
{
Fraction temp=ToFraction(strValue);
Initialize(temp.Numerator, temp.Denominator);
}
public Fraction(long iNumerator, long iDenominator)
{
Initialize(iNumerator, iDenominator);
}
/// <summary>
/// Internal function for constructors
/// </summary>
private void Initialize(long iNumerator, long iDenominator)
{
Numerator=iNumerator;
Denominator=iDenominator;
ReduceFraction(this);
}
/// <summary>
/// Properites
/// </summary>
public long Denominator
{
get
{ return m_iDenominator; }
set
{
if (value!=0)
m_iDenominator=value;
else
throw new FractionException("Denominator cannot be assigned a ZERO Value");
}
}
public long Numerator
{
get
{ return m_iNumerator; }
set
{ m_iNumerator=value; }
}
public long Value
{
set
{ m_iNumerator=value;
m_iDenominator=1; }
}
/// <summary>
/// The function returns the current Fraction object as double
/// </summary>
public double ToDouble()
{
return ( (double)this.Numerator/this.Denominator );
}
/// <summary>
/// The function returns the current Fraction object as a string
/// </summary>
public override string ToString()
{
string str;
if ( this.Denominator==1 )
str=this.Numerator.ToString();
else
str=this.Numerator + "/" + this.Denominator;
return str;
}
/// <summary>
/// The function takes an string as an argument and returns its corresponding reduced fraction
/// the string can be an in the form of and integer, double or fraction.
/// e.g it can be like "123" or "123.321" or "123/456"
/// </summary>
public static Fraction ToFraction(string strValue)
{
int i;
for (i=0;i<strValue.Length;i++)
if (strValue[i]=='/')
break;
if (i==strValue.Length) // if string is not in the form of a fraction
// then it is double or integer
return ( Convert.ToDouble(strValue));
//return ( ToFraction( Convert.ToDouble(strValue) ) );
// else string is in the form of Numerator/Denominator
long iNumerator=Convert.ToInt64(strValue.Substring(0,i));
long iDenominator=Convert.ToInt64(strValue.Substring(i+1));
return new Fraction(iNumerator, iDenominator);
}
/// <summary>
/// The function takes a floating point number as an argument
/// and returns its corresponding reduced fraction
/// </summary>
public static Fraction ToFraction(double dValue)
{
try
{
checked
{
Fraction frac;
if (dValue%1==0) // if whole number
{
frac=new Fraction( (long) dValue );
}
else
{
double dTemp=dValue;
long iMultiple=1;
string strTemp=dValue.ToString();
while ( strTemp.IndexOf("E")>0 ) // if in the form like 12E-9
{
dTemp*=10;
iMultiple*=10;
strTemp=dTemp.ToString();
}
int i=0;
while ( strTemp[i]!='.' )
i++;
int iDigitsAfterDecimal=strTemp.Length-i-1;
while ( iDigitsAfterDecimal>0 )
{
dTemp*=10;
iMultiple*=10;
iDigitsAfterDecimal--;
}
frac=new Fraction( (int)Math.Round(dTemp) , iMultiple );
}
return frac;
}
}
catch(OverflowException)
{
throw new FractionException("Conversion not possible due to overflow");
}
catch(Exception)
{
throw new FractionException("Conversion not possible");
}
}
/// <summary>
/// The function replicates current Fraction object
/// </summary>
public Fraction Duplicate()
{
Fraction frac=new Fraction();
frac.Numerator=Numerator;
frac.Denominator=Denominator;
return frac;
}
/// <summary>
/// The function returns the inverse of a Fraction object
/// </summary>
public static Fraction Inverse(Fraction frac1)
{
if (frac1.Numerator==0)
throw new FractionException("Operation not possible (Denominator cannot be assigned a ZERO Value)");
long iNumerator=frac1.Denominator;
long iDenominator=frac1.Numerator;
return ( new Fraction(iNumerator, iDenominator));
}
/// <summary>
/// Operators for the Fraction object
/// includes -(unary), and binary opertors such as +,-,*,/
/// also includes relational and logical operators such as ==,!=,<,>,<=,>=
/// </summary>
public static Fraction operator -(Fraction frac1)
{ return ( Negate(frac1) ); }
public static Fraction operator +(Fraction frac1, Fraction frac2)
{ return ( Add(frac1 , frac2) ); }
public static Fraction operator +(int iNo, Fraction frac1)
{ return ( Add(frac1 , new Fraction(iNo) ) ); }
public static Fraction operator +(Fraction frac1, int iNo)
{ return ( Add(frac1 , new Fraction(iNo) ) ); }
public static Fraction operator +(double dbl, Fraction frac1)
{ return ( Add(frac1 , Fraction.ToFraction(dbl) ) ); }
public static Fraction operator +(Fraction frac1, double dbl)
{ return ( Add(frac1 , Fraction.ToFraction(dbl) ) ); }
public static Fraction operator -(Fraction frac1, Fraction frac2)
{ return ( Add(frac1 , -frac2) ); }
public static Fraction operator -(int iNo, Fraction frac1)
{ return ( Add(-frac1 , new Fraction(iNo) ) ); }
public static Fraction operator -(Fraction frac1, int iNo)
{ return ( Add(frac1 , -(new Fraction(iNo)) ) ); }
public static Fraction operator -(double dbl, Fraction frac1)
{ return ( Add(-frac1 , Fraction.ToFraction(dbl) ) ); }
public static Fraction operator -(Fraction frac1, double dbl)
{ return ( Add(frac1 , -Fraction.ToFraction(dbl) ) ); }
public static Fraction operator *(Fraction frac1, Fraction frac2)
{ return ( Multiply(frac1 , frac2) ); }
public static Fraction operator *(int iNo, Fraction frac1)
{ return ( Multiply(frac1 , new Fraction(iNo) ) ); }
public static Fraction operator *(Fraction frac1, int iNo)
{ return ( Multiply(frac1 , new Fraction(iNo) ) ); }
public static Fraction operator *(double dbl, Fraction frac1)
{ return ( Multiply(frac1 , Fraction.ToFraction(dbl) ) ); }
public static Fraction operator *(Fraction frac1, double dbl)
{ return ( Multiply(frac1 , Fraction.ToFraction(dbl) ) ); }
public static Fraction operator /(Fraction frac1, Fraction frac2)
{ return ( Multiply( frac1 , Inverse(frac2) ) ); }
public static Fraction operator /(int iNo, Fraction frac1)
{ return ( Multiply( Inverse(frac1) , new Fraction(iNo) ) ); }
public static Fraction operator /(Fraction frac1, int iNo)
{ return ( Multiply( frac1 , Inverse(new Fraction(iNo)) ) ); }
public static Fraction operator /(double dbl, Fraction frac1)
{ return ( Multiply( Inverse(frac1) , Fraction.ToFraction(dbl) ) ); }
public static Fraction operator /(Fraction frac1, double dbl)
{ return ( Multiply( frac1 , Fraction.Inverse( Fraction.ToFraction(dbl) ) ) ); }
public static bool operator ==(Fraction frac1, Fraction frac2)
{ return frac1.Equals(frac2); }
public static bool operator !=(Fraction frac1, Fraction frac2)
{ return ( !frac1.Equals(frac2) ); }
public static bool operator ==(Fraction frac1, int iNo)
{ return frac1.Equals( new Fraction(iNo)); }
public static bool operator !=(Fraction frac1, int iNo)
{ return ( !frac1.Equals( new Fraction(iNo)) ); }
public static bool operator ==(Fraction frac1, double dbl)
{ return frac1.Equals( new Fraction(dbl)); }
public static bool operator !=(Fraction frac1, double dbl)
{ return ( !frac1.Equals( new Fraction(dbl)) ); }
public static bool operator<(Fraction frac1, Fraction frac2)
{ return frac1.Numerator * frac2.Denominator < frac2.Numerator * frac1.Denominator; }
public static bool operator>(Fraction frac1, Fraction frac2)
{ return frac1.Numerator * frac2.Denominator > frac2.Numerator * frac1.Denominator; }
public static bool operator<=(Fraction frac1, Fraction frac2)
{ return frac1.Numerator * frac2.Denominator <= frac2.Numerator * frac1.Denominator; }
public static bool operator>=(Fraction frac1, Fraction frac2)
{ return frac1.Numerator * frac2.Denominator >= frac2.Numerator * frac1.Denominator; }
/// <summary>
/// overloaed user defined conversions: from numeric data types to Fractions
/// </summary>
public static implicit operator Fraction(long lNo)
{ return new Fraction(lNo); }
public static implicit operator Fraction(double dNo)
{ return new Fraction(dNo); }
public static implicit operator Fraction(string strNo)
{ return new Fraction(strNo); }
/// <summary>
/// overloaed user defined conversions: from fractions to double and string
/// </summary>
public static explicit operator double(Fraction frac)
{ return frac.ToDouble(); }
public static implicit operator string(Fraction frac)
{ return frac.ToString(); }
/// <summary>
/// checks whether two fractions are equal
/// </summary>
public override bool Equals(object obj)
{
Fraction frac=(Fraction)obj;
return ( Numerator==frac.Numerator && Denominator==frac.Denominator);
}
/// <summary>
/// returns a hash code for this fraction
/// </summary>
public override int GetHashCode()
{
return ( Convert.ToInt32((Numerator ^ Denominator) & 0xFFFFFFFF) ) ;
}
/// <summary>
/// internal function for negation
/// </summary>
private static Fraction Negate(Fraction frac1)
{
long iNumerator=-frac1.Numerator;
long iDenominator=frac1.Denominator;
return ( new Fraction(iNumerator, iDenominator) );
}
/// <summary>
/// internal functions for binary operations
/// </summary>
private static Fraction Add(Fraction frac1, Fraction frac2)
{
try
{
checked
{
long iNumerator=frac1.Numerator*frac2.Denominator + frac2.Numerator*frac1.Denominator;
long iDenominator=frac1.Denominator*frac2.Denominator;
return ( new Fraction(iNumerator, iDenominator) );
}
}
catch(OverflowException)
{
throw new FractionException("Overflow occurred while performing arithemetic operation");
}
catch(Exception)
{
throw new FractionException("An error occurred while performing arithemetic operation");
}
}
private static Fraction Multiply(Fraction frac1, Fraction frac2)
{
try
{
checked
{
long iNumerator=frac1.Numerator*frac2.Numerator;
long iDenominator=frac1.Denominator*frac2.Denominator;
return ( new Fraction(iNumerator, iDenominator) );
}
}
catch(OverflowException)
{
throw new FractionException("Overflow occurred while performing arithemetic operation");
}
catch(Exception)
{
throw new FractionException("An error occurred while performing arithemetic operation");
}
}
/// <summary>
/// The function returns GCD of two numbers (used for reducing a Fraction)
/// </summary>
private static long GCD(long iNo1, long iNo2)
{
// take absolute values
if (iNo1 < 0) iNo1 = -iNo1;
if (iNo2 < 0) iNo2 = -iNo2;
do
{
if (iNo1 < iNo2)
{
long tmp = iNo1; // swap the two operands
iNo1 = iNo2;
iNo2 = tmp;
}
iNo1 = iNo1 % iNo2;
} while (iNo1 != 0);
return iNo2;
}
/// <summary>
/// The function reduces(simplifies) a Fraction object by dividing both its numerator
/// and denominator by their GCD
/// </summary>
public static void ReduceFraction(Fraction frac)
{
try
{
if (frac.Numerator==0)
{
frac.Denominator=1;
return;
}
long iGCD=GCD(frac.Numerator, frac.Denominator);
frac.Numerator/=iGCD;
frac.Denominator/=iGCD;
if ( frac.Denominator<0 ) // if -ve sign in denominator
{
//pass -ve sign to numerator
frac.Numerator*=-1;
frac.Denominator*=-1;
}
} // end try
catch(Exception exp)
{
throw new FractionException("Cannot reduce Fraction: " + exp.Message);
}
}
} //end class Fraction
/// <summary>
/// Exception class for Fraction, derived from System.Exception
/// </summary>
public class FractionException : Exception
{
public FractionException() : base()
{}
public FractionException(string Message) : base(Message)
{}
public FractionException(string Message, Exception InnerException) : base(Message, InnerException)
{}
} //end class FractionException
} //end namespace Mehroz
正如@Tillito 在评论中指出的那样,我仔细检查了以下代码:
using System.IO;
using System;
using Mehroz;
class Program
{
static void Main()
{
double d = .5;
string str = new Fraction(d).ToString();
Console.WriteLine(str);
}
}
哪些输出:
1/2
关于c# - 在 C# 中将 double 转换为分数作为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7564906/
直接从 Python 代码运行 pylint 时,我似乎无法获得任何返回值。从命令行运行它会生成一个漂亮的报告,在底部有一个总结分数。 我已经尝试将“Run”的返回值放入一个变量中,并获取它的“rep
我是 Python 新手,正在尝试学习单词检测。我有一个带有单词的数据框 sharina['transcript'] Out[25]: 0 thank you for calling my
http://jsfiddle.net/q8P7Y/ 我在最后显示最终分数时遇到问题,有很多方法可以做到这一点,但我不确定什么是最好的。 正如你所看到的,下一个按钮只是 div 的显示/隐藏,而不是页
我使用滑动 slider 并有计数器分数。它计数很好,但我需要计数 =(所有幻灯片 - 1)。例如,如果我有 20 张幻灯片,我想显示总数 19。有什么办法可以做到这一点吗?我使用他们网站上的常规 j
我使用滑动 slider 并有计数器分数。它计数很好,但我需要计数 =(所有幻灯片 - 1)。例如,如果我有 20 张幻灯片,我想显示总数 19。有什么办法可以做到这一点吗?我使用他们网站上的常规 j
我试图在按下按钮时添加分数,分数显示在 JTextField 中,但是当按下按钮时,分数会添加,它显示为 0。我有一个存储分数的整数字段 private int score=0; yesButton
我可以在选项(单选按钮)随机播放之前计算分数/分数,如下面的代码所示。在Collection.shuffle()之前,选项是固定的,因为 CorrectChoice将始终分配给c2单选按钮。那么我可以
我在这里的代码只能得到87%的代码,因为“带有非正参数的加法参数什么也没做。我该如何解决呢?我尝试了更多的方法,但是我什至无法解决此错误在同学的帮助下 说明是: 对于此分配,您将创建一个存储分数的类。
昨天,我尝试以一种方式执行此操作...今天我尝试另一种方式,但仍然卡住了。我必须找到一种使用整数除法和取模来做到这一点的方法。这是我的代码,后面是错误消息。 public int evaluateFr
我这里有一些特殊字符: http://209.141.56.244/test/char.php 但是当我在这里通过 ajax 抓取这个文件时,它们显示为 back ?标记: http://209.14
我得到了一张图表 G与 n顶点,标记自 1至 n (2 a_1 -> a_2 -> ... a_k -> n A然后将占据 1 的所有“子节点”节点, a_1 , ... a_x (其中 x = ce
我有一个看起来像这样的 mongodb 集合: db.scores.insert({"name": "Bob", value: 96.3, timeStamp:'2010-9-27 9:32:00'}
我试图更好地了解 lucene 如何对我的搜索进行评分,以便我可以对我的搜索配置或文档内容进行必要的调整。 以下是分数明细的一部分。 产品: 0.34472802 = queryWeight,
在我网站上用户生成的帖子下,我有一个类似亚马逊的评级系统: Was this review helpful to you: Yes | No 如果有投票,我会在该行上方显示结果,如下所示:
对于我的项目,我需要找出哪些搜索结果被视为“良好”匹配。目前,分数因查询而异,因此需要以某种方式对它们进行标准化。标准化分数将允许选择高于给定阈值的结果。 我为 Lucene 找到了几个解决方案: h
我有一个由 57 个变量组成的数据文件。由于测量水平不均匀,我想将其中的大约 12 个转换为 z 分数。我查找了互联网资源和帮助文件。一个互联网资源建议我需要 Rbasic 包(不存在)。我使用了 s
我对 SOLR 核心运行查询并使用过滤器限制结果例如 fq: {!frange l=0.7 }query($q)。我知道 SOLR 分数不有绝对意义,但是0.7(只是一个例子)是计算出来的基于用户输入
我想找到不同的方法来解决我遇到的现实生活问题:想象一下进行一场比赛或一场游戏,在此期间用户收集积分。您必须构建一个查询来显示具有最佳“n”分数的用户列表。 我举一个例子来澄清。假设这是用户表,其中包含
我有很多 wiki 页面,我想训练一个分类器,看看是否可以通过一些特征(包括段落的位置和段落的 lucene 分数)来确定重点搜索的位置。我尝试将每个段落视为一个文档,这使我能够获得每个段落的 luc
我是 R 编程新手,在使用一些基本代码时遇到问题。 我有一个包含以下列的数据框:条件(因子)、用户(因子)和灵敏度(int)。对于每个用户有 20 个敏感项。我需要为每个用户创建一个具有标准化敏感度分
我是一名优秀的程序员,十分优秀!