首页 > 解决方案 > 测试程序是否正常运行

问题描述

我有一个程序,它基本上说用户输入是在矩形边缘内部、外部还是在矩形边缘上,现在我已经为这个程序编写了一个测试,它应该告诉用户测试/测试是否成功和我想对 xy 表中的每个点进行测试,然后最后判断所有测试是否成功。

我遇到的问题是我不确定如何将它放在基本代码中,以便测试能够正常工作。它应该在开头还是结尾(因为程序在告诉用户点所在的位置后退出)?我应该为测试做一个数组吗?感谢任何帮助如何在基本代码中编写代码:

标签: c

解决方案


首先,您应该检查x1 < x2y1 < y2根据需要交换坐标,使点 (x1, y1) 位于左下方,点 (x2, y2) 位于右上方。

然后检查该点是否在框外

if(x < x1 || x > x2 || y < y1 || y > y2) {
    // outside the box
}

然后检查该点是否在框内

else if(x > x1 && x < x2 && y > y1 && y < y2) {
    // inside the box
}

这留下了这种情况

else {
    // on the box boundary
}

奇怪的是,该函数通过使用它们作为局部变量来覆盖它传递的任何参数。所以当函数返回时坐标会丢失。最好在调用函数之前输入数据,或者将指针传递给将包含数据的变量。


编辑

这是一种方法,尽管有很多方法可以改进代码。使用该double类型的一个困难是浮点数编码的不精确性。请注意,代码避免使用==相等测试。在本例中这可能不是问题,但如果该点已被计算并且理论上应该恰好位于框边界上,则测试可能无法检测到这一点。

#include <stdio.h>

enum { INSIDE, OUTSIDE, EDGE };

int throw_at_rectangle(double x, double y, double x1, double y1, double x2, double y2)
{
    if(x < x1 || x > x2 || y < y1 || y > y2) {
        // outside the box
        return OUTSIDE;
    }

    if(x > x1 && x < x2 && y > y1 && y < y2) {
        // inside the box
        return INSIDE;
    }

    // on the box boundary
    return EDGE;
}

int main(void) {

    double x1, y1;
    double x2, y2;
    double x, y;
    double temp;

    // First corner (bottom left) of the rectangle
    printf("Choose x and y for the first corner that the rectangle should start:\n");
    scanf("%lf%lf", &x1, &y1);

    // Opposite corner(top right) that should make the rectangle possible 
    printf("Choose x and y for the second corner that the rectangle should end:\n");
    scanf("%lf%lf", &x2, &y2);

    // The position of the point that should be checked
    printf("Choose the x and y that should be checked:\n");
    scanf("%lf%lf", &x, &y);

    if(x1 > x2) {
        temp = x1;
        x1 = x2;
        x2 = temp;
    }

    if(y1 > y2) {
        temp = y1;
        y1 = y2;
        y2 = temp;
    }

    switch(throw_at_rectangle(x, y, x1, y1, x2, y2)) {
        case OUTSIDE:
            puts("outside the box");
            break;
        case INSIDE:
            puts("inside the box");
            break;
        default:
            puts("on the boundary");
    }

    return 0;
}

推荐阅读