![](/img/trans.png)
[英]Boolean OR statement returns FALSE even though one of the sides is TRUE
[英]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 true
了return true
行-但这仅将堆栈向上返回了happyNumber方法的堆栈....,然后单击了return false
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.