gpt4 book ai didi

c# - 即使 if 语句为真,函数也返回假

转载 作者:太空宇宙 更新时间:2023-11-03 21:21:23 25 4
gpt4 key购买 nike

这里是问题所在: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 子句在第 4 次运行中为真。您可以在 if(result == 1.0) 设置断点来检查它。那么为什么我的函数返回 false 呢?

最佳答案

您不必要地转换为替身。将 result 设为 int 而不是 double (或者如果您担心结果会变成 long对于 int 来说太大了)。将对 Math.Pow 的调用替换为手动平方 item,如下所示:

result += item * item;

控制流不进入 if(result == 1.0) block 的原因是浮点值在内部表示的方式。测试 double 之间的相等性是有问题的,因此(在这种情况下)您应该完全避免使用它们,因为它们是不需要的。

这里还有一个递归调用:

happyNumber((int)result);

但是,该调用没有任何作用,因为您实际上并未对返回值执行任何操作。考虑将该行替换为:

return happyNumber((int)result);

这将返回递归调用的值,而不是仅仅丢弃它。

关于c# - 即使 if 语句为真,函数也返回假,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30443517/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com