How to resolve the error: Cannot implicitly convert type `long' to `bool'?
How to resolve the error: Cannot implicitly convert type `long' to `bool'?
using System;
using System.Linq;
namespace Problem
{
class Prog
{
public static void Main(string[] args)
{
long t= long.Parse(Console.ReadLine());
while (t-->0)
{
long n, even = 0, odd = 0, a;
n = long.Parse(Console.ReadLine());
for (long i = 0; i < n; i++)
{
a = long.Parse(Console.ReadLine());
if (a % 2)
odd++;
else
even++;
}
Console.WriteLine((even < odd) ? even : odd);
}
}
}
}
由于我是 C# 的新手,所以我一直在使用这段代码来解决 hackerearth 中的一个问题,所以一直在练习,但我并没有真正了解如何解决这个错误说:
solution.cs(21,25): error CS0029: Cannot implicitly convert type 'long' to 'bool'
Compilation failed: 1 error(s), 0 warnings`
if
语句期望 bool
检查,在你的情况下 a % 2
returns 只是一个 long
数字,因为 a
是 long
.
您只需在 if
语句中写一个 boolean expression
。
if (a % 2 != 0)
通常当错误消息显示
Cannot implicitly convert X to bool
这通常意味着它需要一个布尔表达式,所以你应该检查你有 if
语句和循环的代码,并检查你是否输入了错误的内容。这些是编译器通常期望布尔表达式的地方。
在您的编码中 if (a % 2)
是错误的,请注意 a % 2
是 return 长数字,而不是 true/false 值。
using System;
using System.Linq;
namespace Problem
{
class Prog
{
public static void Main(string[] args)
{
long t= long.Parse(Console.ReadLine());
while (t-->0)
{
long n, even = 0, odd = 0, a;
n = long.Parse(Console.ReadLine());
for (long i = 0; i < n; i++)
{
a = long.Parse(Console.ReadLine());
if (a % 2)
odd++;
else
even++;
}
Console.WriteLine((even < odd) ? even : odd);
}
}
}
}
由于我是 C# 的新手,所以我一直在使用这段代码来解决 hackerearth 中的一个问题,所以一直在练习,但我并没有真正了解如何解决这个错误说:
solution.cs(21,25): error CS0029: Cannot implicitly convert type 'long' to 'bool'
Compilation failed: 1 error(s), 0 warnings`
if
语句期望 bool
检查,在你的情况下 a % 2
returns 只是一个 long
数字,因为 a
是 long
.
您只需在 if
语句中写一个 boolean expression
。
if (a % 2 != 0)
通常当错误消息显示
Cannot implicitly convert X to bool
这通常意味着它需要一个布尔表达式,所以你应该检查你有 if
语句和循环的代码,并检查你是否输入了错误的内容。这些是编译器通常期望布尔表达式的地方。
在您的编码中 if (a % 2)
是错误的,请注意 a % 2
是 return 长数字,而不是 true/false 值。