簡體   English   中英

即使if語句為true,函數也會返回false

[英]Functions returns false even when the if statement is true

這是問題所在: https : //leetcode.com/problems/happy-number/

我的解決方案:

static int count = 0; 
public static void Main(string[] args)
{
    Console.WriteLine(happyNumber(19));
    Console.ReadLine(); 
}

public static bool happyNumber(int  a)
{
    double result = 0;
    Stack<int> stapel = new Stack<int>(); 
    //Split the integer into single digits and save them in a stack
    while (a.ToString().Count() > 1)
    {
        stapel.Push(a % 10);
        a = a / 10;
    }
    if (a.ToString().Count() == 1)
    {
        stapel.Push(a);
    }
    // Add the square of the digits to get the result
    foreach (var item in stapel)
    {
        result += Math.Pow((double)item, 2);
    }
    // Check if it's a happy number
    if(result == 1.0)
    {
        return true;
    }
    // counter to stop if it is a endless loop
    else if(count < 100)
    {
        count++;
        happyNumber((int)result);
    }
    return false;
}

因此,輸入19是一個幸福數,而if子句在第四輪中為true。 您可以在if(result == 1.0)處設置一個斷點進行檢查。 那么為什么我的函數返回false呢?

您的函數是遞歸的,但是您對遞歸調用的結果不做任何事情。

如果您更改:

happyNumber((int)result);

至:

return happyNumber((int)result);

那么您的19的結果為true 比較浮點數還可能存在其他問題,但這可能是您的主要問題!

您不必要將其翻倍。 result設為int而不是double (或將其設為long如果您擔心結果對於int而言會太大)。 Math.Pow的調用替換為手動平方的item ,如下所示:

result += item * item;

控制流未進入if(result == 1.0)塊的原因是由於浮點值在內部表示的方式。 測試double s之間的相等性是有問題的,因此(在這種情況下)您可能應該避免完全使用它們,因為它們是不必要的。

您還可以在此處進行遞歸調用:

happyNumber((int)result);

但是,該調用不會執行任何操作,因為您實際上並沒有對返回值做任何事情。 考慮用以下方式替換該行:

return happyNumber((int)result);

這將返回遞歸調用的值,而不僅僅是丟棄它。

發生這種情況是因為您的happyNumber方法調用了自己(最后一行的第3行),然后從該調用中return truereturn true行-但這僅將堆棧向上返回了happyNumber方法的堆棧....,然后單擊了return false

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM