用双坐标计算点的距离

时间:2016-12-26 20:08:02

标签: c++ visual-c++ console-application

当我写一个c ++程序时,我遇到了问题。简而言之,我的程序输入是一个整数,它是我必须输入的坐标数。我有一个算法计算所有点之间的传递距离。这是我的算法:

#include<iostream>
#include<iomanip>
#include<cmath>

using namespace std;

const double PI = 3.14;
const double rightXLimit = 5;
const double leftXLimit = -5;
const double topYLimit = 2;
const double bottomYLimit = -2;
const int ARR_SIZE = 100;

bool IsPointInRules(double x, double y)
{
    if ((x >= leftXLimit && x <= rightXLimit) && (y >= bottomYLimit && y <= topYLimit))
    {
        return true;
    }
    return false;
}

double checkLimitsAndDistCalc(double x, double y, double x1, double y1)
{
    if (!(IsPointInRules(x, y) || IsPointInRules(x1, y1)))
    {
        return 0;
    }
    else if (IsPointInRules(x, y) && (!IsPointInRules(x1, y1)))
    {
        if (x1 <= leftXLimit)
        {
            x1 = leftXLimit;
        }
        if (x1 >= rightXLimit)
        {
            x1 = rightXLimit;
        }
        if (y1 <= bottomYLimit)
        {
            y1 = bottomYLimit;
        }
        if (y1 >= topYLimit)
        {
            y1 = topYLimit;
        }
    }
    else if ((!IsPointInRules(x, y)) && IsPointInRules(x1, y1))
    {
        if (x <= leftXLimit)
        {
            x = leftXLimit;
        }
        if (x >= rightXLimit)
        {
            x = rightXLimit;
        }
        if (y <= bottomYLimit)
        {
            y = bottomYLimit;
        }
        if (y >= topYLimit)
        {
            y = topYLimit;
        }
    }
    double distance = sqrt(pow(x1 - x, 2) + pow(y1 - y, 2));
    double result = ((PI * distance / 2) + distance) / 2;

    //cout << setw(3) << x << setw(3) << y << setw(3) << x1 << setw(3) << y1 << " --> " << distance << " --> " << result << endl;

    return result;
}

double calculateDistance(double* arrOne, double* arrTwo, int n)
{
    double finalResult = 0;
    for (int i = 0; i < n - 1; i++)
    {
        double getDistance = checkLimitsAndDistCalc(arrOne[i], arrTwo[i], arrOne[i + 1], arrTwo[i + 1]);
        finalResult += getDistance;
    }
    return finalResult;
}

int main()
{
    double coordsArrX[ARR_SIZE];
    double coordsArrY[ARR_SIZE];
    int n;

    cin >> n;

    for (int i = 0; i < n; i++)
    {
        cin >> coordsArrX[i];
        cin >> coordsArrY[i];
    }

    cout << setprecision(3) << fixed << calculateDistance(coordsArrX, coordsArrY, n) << '\n';

}

问题是当我输入像坐标这样的整数时距离是错误的,但是输入双倍时距离是正确的,我找不到问题所在。在这里,我尝试了一些自动测试:

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

  

问题是,当我输入像坐标这样的整数时,距离是错误的,但是当输入双倍时,距离是正确的,我找不到问题所在。

这是一个错误的结论。无论使用看起来是整数还是浮点数输入坐标,输出都是相同的。

使用

获得的输出
7
0 0
0 3
-2 4
-1 1
-3 -1
4 1
6 3

与使用

相同
7
0.0 0.0
0.0 3.0
-2.0 4.0
-1.0 1.0
-3.0 -1.0
4.0 1.0
6.0 3.0

http://ideone.com/fxgbga处查看使用浮点输入的输出。

您的程序中似乎还有其他内容无法正常运行。