【发布时间】:2022-01-02 02:24:43
【问题描述】:
1 - 常数,n - 整数。我总是分享 1/n
例子:
- 1/n (n = 3), 1/3 = 0,333333,所以这个数的周期是(3)。
- 1/n (n = 7), 1/7 = 0,1428571428571429, 这个数字的周期是 (1428571)。
- 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。它包含重复的数字,但不包含句号。这就是我的意思