C# C函数错误(对象引用)
非常直截了当的问题,我得到了一个错误,我不知道如何解决,在Visual C Express中,当我在main中调用Romberg函数时,我在适当的行中提供了错误消息。我试过用这个,隆伯格也是,但没用。我应该怎么做C# C函数错误(对象引用),c#,function,object,reference,C#,Function,Object,Reference,非常直截了当的问题,我得到了一个错误,我不知道如何解决,在Visual C Express中,当我在main中调用Romberg函数时,我在适当的行中提供了错误消息。我试过用这个,隆伯格也是,但没用。我应该怎么做 using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Romberg2 { class test { // the
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Romberg2
{
class test
{
// the function
double f(double x)
{
double f;
f=8*(Math.Sqrt(1-x*x)-x);
return f;
}
// The Integration function
void Romberg(double a, double b, int n, double[,] R)
{
int i, j, k;
double h, sum;
h = b - a;
R[0,0]=(h/2)*(f(a)+f(b));
for (i=1; i<=n; i++)
{
h=h/2;
sum=0;
for (k=1; k <= (Math.Pow(2.0,i)-1); k +=2)
sum +=f(a+k*h);
R[i,0]=R[i-1,0]/2+sum*h;
for(j=1; j<=i; j++)
R[i,j]=R[i,j-1]+(R[i,j-1]-R[i-1,j-1])/(Math.Pow(4.0,j)-1);
}
}
static void main(int argc, char [] argv)
{
double[,] R = new double [10,10];
int n=5, digits=13;
double a=0, b=1/Math.Sqrt(2.0);
// Call the integrating function
Romberg(a, b, n, R);//ERROR: An object reference is required for the non-static field, method, or property
// Printout the diagram
for(int i=0; i<n; i++)
{
for(int j=0; j<=i; j++)
{
Console.WriteLine(R[i,j] + " ");
}
Console.WriteLine("\n");
}
}
}
}
你需要使你的Romberg函数是静态的,或者你可以把它封装在它自己的类中,实例化并执行它。Romberg不是一个静态方法,所以你应该通过一个实例使用new关键字调用它
new test().Romberg(a, b, n, R);
或者干脆把它变成一个静态函数
static void Romberg(double a, double b, int n, double[,] R)
main是静态的,因此不能调用实例方法。将Romberg声明为静态,或创建测试实例并使用该实例:
var inst = new test();
inst.Romberg(a, b, n, R);
有关更多信息,请查看MSDN上的文章,Main是一种静态方法,Roomberg是一种实例方法。在Main中创建一个新的类实例并通过实例调用它,或者使Roomberg也是静态的。您需要在实例上调用该方法。该方法属于该类的实例
var inst = new test();
inst.Romberg(q, w, e, R);
试试这个。叫龙贝加,b,n,R;您必须首先创建测试类对象。Romberg是一种实例方法
test obj=new test();
obj.Romberg(a, b, n, R);
您正在尝试从未初始化的类调用方法
static void Romberg(double a, double b, int n, double[,] R)
三个问题:
1 Main的格式不正确。它需要采用以下格式之一:
static void Main() {...}
static void Main(string[] args) {... }
static int Main() {...}
static int Main(string [] args) {...}
只需将其更改为“静态void Main”
2使Romberg方法保持静态
static void Romberg(double a, double b, int n, double[,] R)
3使f方法为静态:
static double f(double x)
将静态添加到void Romberg->static voidRomberg@Marc最后,我也知道了答案: