C++ 在另一个函数中使用一个函数中的变量
我制作了一个计算形状的代码。输入角数。然后是每个角的坐标。由此,它将给出每个角之间的距离、周长、面积和质心。我得到了面积,它可以计算为e。但当我尝试使用质心中的“e”来计算xy坐标时,它停止工作。在区域中,我初始化e=0。在我的形心函数中,它取e为0,所以当我尝试用“e”除以1时,程序停止工作C++ 在另一个函数中使用一个函数中的变量,c++,function,variables,C++,Function,Variables,我制作了一个计算形状的代码。输入角数。然后是每个角的坐标。由此,它将给出每个角之间的距离、周长、面积和质心。我得到了面积,它可以计算为e。但当我尝试使用质心中的“e”来计算xy坐标时,它停止工作。在区域中,我初始化e=0。在我的形心函数中,它取e为0,所以当我尝试用“e”除以1时,程序停止工作 void Area(int x[], int y[], int corners, int e, int g) { e = 0; //Initialise e for (g = 0; g&
void Area(int x[], int y[], int corners, int e, int g)
{
e = 0; //Initialise e
for (g = 0; g<(corners - 1); g++)
{
e += ((x[g] * y[g + 1]) - (x[g + 1] * y[g]));
}
e += ((x[corners - 1] * y[0]) - (x[0] * y[corners - 1]));
e *= -0.5;
cout << "The Area is" << " " << e << endl;
}
void Centroid(int x[], int y[], int wx, int wy,int corners,int g,int e)
{
wx = 0;
wy = 0;
for (g = 0; g < (corners-1); g++)
{
wx += ((x[g] + x[g + 1])*((x[g] * y[g + 1]) - (x[g + 1] * y[g])));
wy += ((y[g] + y[g + 1])*((x[g] * y[g + 1]) - (x[g + 1] * y[g])));
}
wx *= ((1 / (6 * e)));
wy *= ((1 / (6 * e)));
cout << "The Centroid is" << " " << wx << "," << wy << endl;
}
int main()
{
int g, corners, x[100], y[100], r[100], c, e,wx,wy;
cout << "Enter the number of corners";
cin >> corners;
for (g = 0; g<corners; g++)
{
cout << "enter the co ordinates";
cin >> x[g] >> y[g];
cout << "You have entered " << x[g] << " " << y[g] << endl;
}
Distance(x, y, corners, r, c = 0);
Perimeter(r, corners, g, c);
Area(x, y, corners, e = 0, g,wx=00.0,wy=00.0);
/*Centroid(x,y,wx=0,wy=0,corners,g,e);
*/
system("pause");
}
void区域(int x[],int y[],int角点,int e,int g)
{
e=0;//初始化e
对于(g=0;g而言,解决方案是使用指向变量的指针或引用
您需要更改第一行,如下所示:
void Area(int x[], int y[], int corners, int &e, int g)
我认为您需要的是让函数计算值并返回它们。区域
函数的要点是确定区域,并生成结果:
int Area(int[] x, int[] y, int corners) {
int e = 0;
for (int g = 0; g < corners - 1; ++g) { // g is local to this loop
e += ((x[g] * y[g + 1]) - (x[g + 1] * y[g]));
}
e += ((x[corners - 1] * y[0]) - (x[0] * y[corners - 1]));
e *= -0.5;
return e; // give the caller the "answer"
}
然后将其传递到形心
函数:
int wx = 0, wy = 0;
Centroid(x, y, corners, e, wx, wy);
其中质心的定义应如下所示:
void Centroid(int x[], int y[], int corners, int e, int& wx, int& wy)
我们通过引用获取wx
和wy
,这样我们可以返回两个值。更好的方法是让质心
返回一个点
对象:
struct Point {
int x, y;
};
让它自己计算面积:
Point Centroid(int x[], int y[], int corners) {
Point p = {0};
int e = Area(x, y, corners);
// replace all code referencing wx and wy with p.x and p.y
return p;
}
因此,从main
,代码看起来更干净:
Point centroid = Centroid(x, y, corners);
将参数传递给函数背后的想法是,在将每个参数传递给函数之前,先计算其值。否则,您不妨将其声明为函数内部的局部变量。正如@barakmanos所说,您传递的是不需要传递的参数。变量e
、g
、wx
和<代码> Wy 应该都是本地的代码<代码> int <代码>。请在这里调用这些函数的代码。@ CARYGRGGORY这里是我称之为函数的代码。对不起,这不是你的意思。我对C++非常陌生,我们必须把它作为我们模块的一部分。此刻我正试图弄清楚该怎么做,我已经评论了Cytoo。谁是“我们”和什么是“我们的模块”?什么是“链接”?我想你是指参考。好的,我为你解决了这个问题。
Point centroid = Centroid(x, y, corners);