【发布时间】:2022-01-11 22:48:35
【问题描述】:
所以我的代码是检查给定数字是否是“快乐数字”。它将数字的每个数字平方,将它们相加并继续这样做,直到加法的结果为 1(这意味着它 是一个快乐的数字)或直到它得到一个 4(这意味着这不是一个快乐的数字)。
发生的情况是有很多数字会导致无限循环(因此意味着它们不是一个快乐的数字),我想知道如何构造我的代码以便它检测何时发生无限循环?我有一些想法,但都有缺陷。
我的代码如下:
using System;
namespace Happy_numbers_problem
{
class Program
{
static int HappyNumbers(string Number)
{
string Output = Number;
while ((Convert.ToInt32(Output) != 1) && (Convert.ToInt32(Output) != 4))
{
string Result2 = "0";
for (int Index = 0; Index < Output.Length; Index++)
{
string Character = Output.Substring(Index, 1);
int Calc = Convert.ToInt32(Character);
int Result = Calc * Calc;
//Adding Result2 and Result, then turning it into a string.
Result2 = Convert.ToString(Convert.ToInt32(Result2) + Result);
if (Index == (Output.Length) - 1)
{
Output = Result2;
}
}
}
return Convert.ToInt32(Output);
}
static void Main(string[] args)
{
Console.WriteLine("Please enter a number");
string Number = Console.ReadLine();
int Output = HappyNumbers(Number);
if (Output == 1)
{
Console.WriteLine(Number + " is a happy number");
}
else if (Output == 4)
{
Console.WriteLine(Number + " is not a happy number");
}
else
{
Console.WriteLine(Number + " is not a happy number");
}
}
}
}
【问题讨论】:
标签: c# for-loop while-loop infinite-loop