我制作了一个计算形状的代码。您输入角数。然后是每个角落的合作。从这里它将给你每个角落,周长,面积和质心之间的距离。我已经达到了区域,它可以将其计算为e。但是当我尝试在质心中使用“e”来计算xy co ords时,它就会停止工作。在该区域中,我初始化e = 0。在我的质心函数中,它取e为0所以当我尝试将1除以“e”时,程序停止工作。
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");
}
答案 0 :(得分:1)
我认为你想要的是让你的函数计算值并返回它们。 Area
函数的关键点是确定区域,然后产生结果:
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"
}
这样,在您的主要内容中,您可以确定e
是什么:
int e = Area(x, y, corners); // this function does not need g
然后将其传递到您的Centroid
函数:
int wx = 0, wy = 0;
Centroid(x, y, corners, e, wx, wy);
Centroid
的定义应如下所示:
void Centroid(int x[], int y[], int corners, int e, int& wx, int& wy)
我们通过引用获取wx
和wy
,以便我们可以返回两个值。更好的方法是让Centroid
返回Point
个对象:
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);
答案 1 :(得分:0)
解决方案是使用指针或对变量的引用。
您需要更改第一行:
void Area(int x[], int y[], int corners, int &e, int g)