【问题标题】:Return fractional period返回小数周期
【发布时间】:2022-01-02 02:24:43
【问题描述】:

1 - 常数,n - 整数。我总是分享 1/n

例子:

  1. 1/n (n = 3), 1/3 = 0,333333,所以这个数的周期是(3)。
  2. 1/n (n = 7), 1/7 = 0,1428571428571429, 这个数字的周期是 (1428571)。
  3. 1/n (n = 2), 1/2 = 0,5 ,所以这个数字没有句号。

所以我需要编写递归算法,打印或返回周期。我尝试了我的算法,但在某些情况下得到的结果不正确。

using System;

namespace LB_5._2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter number: ");
            int n = int.Parse(Console.ReadLine());            
            GetPeriod(n);
        }
        public static void GetPeriod(int n, int current = 10, int part = 0, string result = "", int next = 0)
        {
            part = current / n;
            string currentCheck = part.ToString();
            result += part;
            next = (current - n * part);                       
            if(result.Contains(((next * 10) / n).ToString()))
            {
                Console.WriteLine(result);
            }
            else
            {
                GetPeriod(n, next * 10, part, result);
            }

        }
    }

}

【问题讨论】:

  • “例如,如果我尝试 1/6” 你是如何尝试的?你在控制台输入1 / 6 ?
  • 使用 1/6 作为输入,抛出 System.FormatException。
  • 程序做什么以及期望的输出是什么?你为什么使用递归
  • @Cid 1 它是一个常数,你写了除以常数的数字。所以输入它的-n,我们检查1/n
  • @GoldenLion 如果你分享 1/19,你得到的结果是 0,0526315789473684。它包含重复的数字,但不包含句号。这就是我的意思

标签: c# recursion fractions


【解决方案1】:

查找模式:查找一位或多位数字,后跟一个句点,然后是一位或多位数字,如果数字重复,则捕获该组。

def repeat(result):    
    pattern=r"\d+\.\d+(\d+)\1"
    matches=re.findall(pattern,result)
    return matches

result=str(1/7)
print(repeat(result))
result=str(1/6)
print(repeat(result)) 
result=str(1/2)
print(repeat(result)) 

输出

0.14285714285714285->['714285'] (this is more accurate, because it repeats)
0.16666666666666666->['6']
0.5->[]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-03
    • 1970-01-01
    • 1970-01-01
    • 2021-04-06
    • 2017-06-15
    • 1970-01-01
    • 2023-03-24
    • 2013-02-23
    相关资源
    最近更新 更多