【问题标题】:How do I detect an infinite loop occuring in my code?如何检测代码中发生的无限循环?
【发布时间】: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


    【解决方案1】:

    问题在于您的 while 条件。如果您的输出 需要 为 1 或 4 以跳出循环并将输出传递给后者进行分析,则必须使用运算符 || 而不是运算符 &amp;&amp;.

    【讨论】:

    • 但这会导致无限循环吗?最终值变为 1,但使用 | |它似乎并没有停止迭代。与出于某种原因使用 && 不同?
    • 使用调试器?确定无限循环会更容易
    • 不必要会导致循环但有机会,因为需要匹配两个条件才能离开循环,而不是一个。
    猜你喜欢
    • 2014-04-08
    • 2014-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-09
    • 1970-01-01
    • 2012-03-15
    • 1970-01-01
    相关资源
    最近更新 更多