我在使用C++编写的代码时遇到问题。编译器向我发送错误C2440,我不知道为什么。这里是代码,问题出现在void main()
区域,特别是在线路R = calloc
和R[i] = calloc
。感谢您的答案。错误C2440无法将void *转换为double **或double *
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <iostream>
using namespace std;
double F (double x);
double G (double x);
double P (double x);
void romberg(double f(double), double a, double b, int n, double **R);
double F (double x)
{
return (1.0/ (1.0 + x));
}
double G (double x)
{
return (exp(x));
}
double P (double x)
{
return (sqrt(x));
}
void romberg(double f(double), double a, double b, int n, double **R)
{
int i, j, k;
double h, sum;
h = b - a;
R[0][0] = 0.5 * h * (f(a) + f(b));
cout << " R[0][0] = ";
cin >> R[0][0];
for (i = 1; i <= n; i++)
{
h *= 0.5;
sum = 0;
for (k = 1; k <= pow(2,i)-1; k+=2)
{
sum += f(a + k * h);
}
R[i][0] = 0.5 * R[i-1][0] + sum * h;
cout << "R[i][0] = ";
cin>>i, R[i][0];
for (j = 1; j <= i; j++)
{
R[i][j] = R[i][j-1] + (R[i][j-1] - R[i-1][j-1])/(pow(4,j)-1);
cout << " R[i][j] = ";
cin>>i, j, R[i][j];
}
}
}
void main()
{
int n = 10;
int i;
double **R;
double F(double), G(double), P(double);
R = calloc((n+1), sizeof(double *));
for (i = 0; i <= n; i++)
R[i] = calloc((n+1), sizeof(double));
cout<<"The first function is F(x) = 1/(1 + x)\n";
romberg(F, 0.0, 2.0,3, R);
cout<<"The second function is G(x) = exp(x)\n";
romberg(G,-1.0, 1.0, 4, R);
cout<<"The third function is P(x) = sqrt(x)\n";
romberg(P,0.0, 1.0, 7, R);
}
决不'无效main'的数据! 'int main'! – aschepler
1.当你必须分配内存时使用'new' 2.你很少需要分配内存(使用标准容器,比如'std :: vector'或者使用智能指针)。 – crashmstr
@crashmstr:不,不要使用'new',永远不要。 –