我需要找到一个浮点数与另一个浮点数的比率,该比率需要是两个整数.例如:
1.5, 3.25"6:13"有谁知道吗?在互联网上搜索,我没有找到这样的算法,也没有找到两个浮点数(只是整数)的最小公倍数或分母的算法.
这是我将使用的最终实现:
public class RatioTest
{
public static String getRatio(double d1, double d2)//1.5, 3.25
{
while(Math.max(d1,d2) < Long.MAX_VALUE && d1 != (long)d1 && d2 != (long)d2)
{
d1 *= 10;//15 -> 150
d2 *= 10;//32.5 -> 325
}
//d1 == 150.0
//d2 == 325.0
try
{
double gcd = getGCD(d1,d2);//gcd == 25
return ((long)(d1 / gcd)) + ":" + ((long)(d2 / gcd));//"6:13"
}
catch (StackOverflowError er)//in case getGDC (a recursively looping method) repeats …Run Code Online (Sandbox Code Playgroud) 我是Python的新手,被要求创建一个程序,该程序将输入作为非负整数n,然后使用连续分数的前n + 1个项来计算e的近似值:
我试图破译这个问题,但无法完全理解它所问的一切。我不是在寻找确切的答案,而是希望有一个例子可以对我有所帮助。
这是确切的问题,
下面是我之前对连续分数所做的代码。
import math
# Get x from user
x = float(input("Enter x = "))
# Calculate initial variables and print
a0 = x//1
r0 = x-a0
print("a0 =", a0, "\tr0 =", r0)
# Calculate ai and ri for i = 1,2,3 and print results
a1 = 1/r0//1
r1 = 1/r0 - a1
print("a1 =", a1, "\tr1 =", r1)
a2 = 1/r1//1
r2 = 1/r1 - a2
print("a2 =", a2, "\tr2 =", r2)
a3 = 1/r2//1 …Run Code Online (Sandbox Code Playgroud) 例如,如果我的函数被调用getlowestfraction(),这就是我期望它做的:
getlowestfraction(0.5) // returns 1, 2 or something along the lines of that
Run Code Online (Sandbox Code Playgroud)
另一个例子:
getlowestfraction(0.125) // returns 1, 8 or something along the lines of that
Run Code Online (Sandbox Code Playgroud)