Rectangle.Intersect(矩形).在功能上有错误吗?

本文关键字:功能上 有错误 Intersect 矩形 Rectangle | 更新日期: 2023-09-27 17:54:24

尝试编写程序,找到许多矩形之间的交集。试图相交的例子矩形(x,y,宽度,高度)-"2 5 5 3"answers"4 7 2 4",答案必须是"4 5 2 2",但程序告诉我,答案是"4 7 2 1",不能!请帮我找出一个错误,我看不出来。我的程序代码:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
namespace MyProgramm
{
 class Rectangles
 {
    private List<Rectangle> List = new List<Rectangle>();
    public void AddRectangle(int X, int Y, int Width, int Height)
    {
        List.Add(new Rectangle(X, Y, Width, Height));
    }
    public int[] CrossRectangles()
    {
        if (List.Count != 0)
        {
            if (List.Count != 1)
            {
                Rectangle answer = List [0];
                for (int i = 1; i < List.Count; i++)
                    answer.Intersect(List[i]);
                return new int[] { answer.X, answer.Y, answer.Width, answer.Height };
            }else
                return new int[] { List.First().X, List.First().Y, List.First().Width, List.First().Height };
        }else 
            return new int[] { 0, 0, 0, 0 };
    }
 }
 class Program
 {
    static void Main(string[] args)
    {
        Rectangles P = new Rectangles();
        P.AddRectangle(2, 5, 5, 3);
        P.AddRectangle(4, 7, 2, 4);
        foreach (int num in P.CrossRectangles())
            Console.WriteLine(num);
    }
 }
}

Rectangle.Intersect(矩形).在功能上有错误吗?

程序正确,正确答案是"4 7 2 1"。

很可能你把第二对参数搞混了,它们是宽度和高度,而不是"右上角"的坐标。

但是把这些矩形画在纸上,你会发现答案实际上是"4 7 2 1"

我看是正确的。

这是一个图形版本:

 123456789   123456789   123456789
1.........  1.........  1.........
2.........  2.........  2.........
3.........  3.........  3.........
4.........  4.........  4.........
5.│││││...  5.........  5.│││││...
6.│││││...  6.........  6.│││││...
7.│││││...  7...──....  7.││┼┼│...
8.........  8...──....  8...──....
9.........  9...──....  9...──....
X.........  X...──....  X...──....

你可以清楚地看到,交点确实在坐标{4,7}处,尺寸为2x1。