gpt4 book ai didi

c# - 在 C# 中检查整数是否为 2 的幂

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

我的程序有什么问题?

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
bool check = isPowerOfTwo(255);
Console.WriteLine(check);
Console.ReadKey();
}

public bool isPowerOfTwo (uint x)
{
while (((x % 2) == 0) && x > 1)
{
x /= 2;
}
return (x == 1);
}
}

我遇到了错误

An object reference is required for the non-static field, method or property.

最佳答案

使方法 isPowerOfTwo 静态:

public static bool isPowerOfTwo (uint x)

Method Main 是静态的,因此您只能在其中调用同一类的静态方法。然而 isPowerOfTwo 目前是一个实例方法,它只能在 Program 类的实例上调用。当然,您也可以在 Main 中创建一个 Program 类的实例并调用它的方法,但这似乎是一种开销。

关于c# - 在 C# 中检查整数是否为 2 的幂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17418676/

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