C# 将BigInteger乘以Double
我的物理老师给全班布置了一项艰巨的任务。我正在尝试创建一个程序来为我计算一些东西。在某一点上,我需要用一个百分比乘以一个分子量。Ulong不能保存6022*10^19这样大的数字,所以我必须使用.NET4.0中的BigInteger。但是,乘法不能应用于BigInteger和double。我只需要整数。有没有办法绕过这个? 代码如下:C# 将BigInteger乘以Double,c#,c#-4.0,console-application,C#,C# 4.0,Console Application,我的物理老师给全班布置了一项艰巨的任务。我正在尝试创建一个程序来为我计算一些东西。在某一点上,我需要用一个百分比乘以一个分子量。Ulong不能保存6022*10^19这样大的数字,所以我必须使用.NET4.0中的BigInteger。但是,乘法不能应用于BigInteger和double。我只需要整数。有没有办法绕过这个? 代码如下: private static BigInteger pencapmoles = BigInteger.Pow(6022/9, 19); private stati
private static BigInteger pencapmoles = BigInteger.Pow(6022/9, 19);
private static BigInteger inkmoles = pencapmoles;
private static BigInteger tries = 0;
private static BigInteger molesinbucket = BigInteger.Pow(26761768, 19);
private static double percentage;
static void Main(string[] args)
{
while (inkmoles > 1)
{
percentage = (double)(inkmoles / molesinbucket);
inkmoles = pencapmoles * percentage;
tries++;
}
Console.WriteLine($"It only took us {tries} tries.");
}
您最好将所有计算切换到
double
或biginger
。C#double
有足够的范围来容纳远大于1019的值,但答案将有一点不精确。几乎可以肯定的是,这将足以解决您的任务
如果切换到biginger
,请先相乘,然后进行除法:
inkmoles = (inkmoles * pencapmoles) / molesinbucket;
将
百分比
强制转换为大整数
。像这样inkmoles=pencapmoles*(BigInteger)百分比代码>为什么要使用BigInteger?这些都是物理量(除了trys
),可以很容易地表示为双精度。只需对所有物理量使用双精度即可。只有当你知道一个事物有多少个时,才可以使用整数。记住,你可以用双精度的科学记数法:double avogadro=6.022E23代码>谢谢你的帮助。用双打解决了我的问题。我从没想过他们能持有这么大的价值。