C# 即使if语句为true,函数也返回false
问题是: 我的解决方案:C# 即使if语句为true,函数也返回false,c#,if-statement,C#,If Statement,问题是: 我的解决方案: 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&l
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;
}
static int count=0;
公共静态void Main(字符串[]args)
{
Console.WriteLine(happyNumber(19));
Console.ReadLine();
}
公共静态布尔happyNumber(int a)
{
双结果=0;
Stack statpel=新堆栈();
//将整数拆分为单个数字并保存在堆栈中
而(a.ToString().Count()>1)
{
静止推力(a%10);
a=a/10;
}
如果(a.ToString().Count()==1)
{
静止推力(a);
}
//将数字的平方相加得到结果
foreach(stapel中的var项目)
{
结果+=数学功率((双)项,2);
}
//看看这是不是一个快乐的数字
如果(结果==1.0)
{
返回true;
}
//如果是一个无止境的循环,则计数器停止
否则,如果(计数<100)
{
计数++;
happyNumber((int)结果);
}
返回false;
}
因此,输入19是一个愉快的数字,if子句在第4次运行时为true。
您可以在
if(result==1.0)
处设置断点来检查它。那么为什么我的函数返回false呢 您的函数是递归的,但不会对递归调用的结果进行任何处理
如果您更改:
happyNumber((int)result);
致:
那么19的结果是
true
。浮点数的比较可能还有其他问题,但这可能是您的主要问题 您的函数是递归的,但不会对递归调用的结果进行任何处理
如果您更改:
happyNumber((int)result);
致:
那么19的结果是
true
。浮点数的比较可能还有其他问题,但这可能是您的主要问题 你不必要地向替补投球。将result
设置为int
而不是double
(或者将其设置为long
,如果您担心结果对于int
来说太大)。将对Math.Pow
的调用替换为手动平方项
,如下所示:
result += item * item;
控制流不进入if(result==1.0)块的原因是浮点值在内部的表示方式。测试double
s之间的相等性是有问题的,因此(在本场景中)您可能应该完全避免使用它们,因为它们是不需要的
这里还有一个递归调用:
happyNumber((int)result);
但是,该调用不起任何作用,因为您实际上没有对返回值进行任何操作。考虑用:替换该行
return happyNumber((int)result);
这将返回递归调用的值,而不仅仅是丢弃它。您不必要地将其转换为double。将
result
设置为int
而不是double
(或者将其设置为long
,如果您担心结果对于int
来说太大)。将对Math.Pow
的调用替换为手动平方项
,如下所示:
result += item * item;
控制流不进入if(result==1.0)块的原因是浮点值在内部的表示方式。测试double
s之间的相等性是有问题的,因此(在本场景中)您可能应该完全避免使用它们,因为它们是不需要的
这里还有一个递归调用:
happyNumber((int)result);
但是,该调用不起任何作用,因为您实际上没有对返回值进行任何操作。考虑用:替换该行
return happyNumber((int)result);
这将返回递归调用的值,而不仅仅是丢弃它。发生这种情况是因为您的happyNumber方法调用自身(最后第三行),然后从该调用中点击
返回true
行-但这只会将堆栈上的一个步骤返回到happyNumber方法。。。。然后点击返回false
之所以会发生这种情况,是因为您的happyNumber方法调用自身(最后第三行),然后从该调用中,它会点击return true
行-但这只会向happyNumber方法返回堆栈上的一步。。。。然后点击返回false
检查(result==1)是否为是,它仍然为真,但我的函数将返回false;检查(result==1)是否为是,它仍然为真,但我的函数将返回false,我将更改它。编辑:啊,现在我明白了。非常感谢,我要换一下。编辑:啊,现在我明白了。非常感谢你。