无法隐式将'ulong'类型转换为'bool'

时间:2021-12-05 16:31:00

I get this error:

我收到此错误:

Cannot implicitly convert type 'ulong' to 'bool'

无法隐式将'ulong'类型转换为'bool'

in here (u*u) for (ulong u = 2; u * u; u++)

在这里(u * u)for(ulong u = 2; u * u; u ++)

chunk of code below.

下面的代码块。

static bool IsPrime(ulong Num)
{
     if (Num < 2) return false;
     else if (Num < 4) return true;
     else if (Num % 2 == 0) return false;
     for (ulong u = 2; u * u; u++)
         if (Num % u == 0) return false;
     return true;
}

1 个解决方案

#1


Check MSDN about for keyword :

检查MSDN关于关键字:

Every for statement defines initializer, condition, and iterator sections. These sections usually determine how many times the loop iterates.

每个for语句都定义了初始化器,条件和迭代器部分。这些部分通常决定循环迭代的次数。

So the second part is a condition and must be implicitly converted to bool. Since long type cannot be converted implicitly, u get a compile time error. I guess it was what you where trying to do:

所以第二部分是一个条件,必须隐式转换为bool。由于long类型无法隐式转换,因此会出现编译时错误。我想这就是你想要做的事情:

static bool IsPrime(ulong Num)
{
   if (Num < 2)
        return false;
   else if (Num < 4)
        return true;
   else if (Num % 2 == 0)
        return false;
   for (ulong u = 2; u * u < Num; u++)
       if (Num % u == 0)
          return false;
   return true;
}

#1


Check MSDN about for keyword :

检查MSDN关于关键字:

Every for statement defines initializer, condition, and iterator sections. These sections usually determine how many times the loop iterates.

每个for语句都定义了初始化器,条件和迭代器部分。这些部分通常决定循环迭代的次数。

So the second part is a condition and must be implicitly converted to bool. Since long type cannot be converted implicitly, u get a compile time error. I guess it was what you where trying to do:

所以第二部分是一个条件,必须隐式转换为bool。由于long类型无法隐式转换,因此会出现编译时错误。我想这就是你想要做的事情:

static bool IsPrime(ulong Num)
{
   if (Num < 2)
        return false;
   else if (Num < 4)
        return true;
   else if (Num % 2 == 0)
        return false;
   for (ulong u = 2; u * u < Num; u++)
       if (Num % u == 0)
          return false;
   return true;
}