2012-11-08 68 views
3

我想問這個函數是否正確。它應該檢查點是否在矩形內,如果是,則打印出來。矩形內的點

#include <stdio.h> 
#include <stdlib.h> 

typedef struct { 
    int x; 
    int y; 
}point; 

typedef struct { 
    point A; 
    point B; 
}rectangle; 

int main() { 
rectangle s; 
point T; 
printf("Enter rectangle A point x coordinate :\n"); 
scanf("%d", &s.A.x); 
printf("Enter rectangle A point y coordinate :\n"); 
scanf("%d", &s.A.y); 
printf("Enter rectangle B point x coordinate :\n"); 
scanf("%d", &s.B.x); 
printf("Enter rectangle B point y coordinate :\n"); 
scanf("%d", &s.B.y);  
printf("\nrectangle - A(%d, %d), B(%d, %d) \n", s.A.x, s.A.y, s.B.x, s.B.y); 

for(int i =0; i<2; i++){ 
printf ("X: "); 
scanf ("%d", &T.x); 
printf ("Y: "); 
scanf ("%d", &T.y); 
} 

int is_inside(point A, point B){ 
if((s.A.x <= T.x) && (T.x <= s.B.x) && (s.A.y <= T.y) && (T.y <= s.B.y)) printf("Point (%d, %d)is inside rectangle \n",T.x, T.y); 
else printf("No"); 
} 
return 0; 
} 

添加整個代碼也許它會更清楚地給你們。

回答

2

你不能使用if (a<=b<=c),因爲它從左到右評估,它會導致你的問題。

第一a<=b計算結果爲01再次相比,第三項c

使用a<=b && b<=c語法

所以,在你的情況下,它會像

if ((s.A.x <= T.x) && (T.x <= s.B.x) && (s.A.y <=T.y)&& (T.y <= s.B.y)) 

該聲明說, s.A.x is less than equal to T.xT.x is less than or equal to s.B.x AND s.A.y less than equal to T.y and T.y is less than equal to s.B.y

7

此功能不正確。它編譯,但它不會做你想做的事*

數學條件,如這一個

x0 <= X <= x1 

都寫在C如下:

x0 <= X && X <= x1 

你的情況應該是這樣的:

if (s.A.x<=T.x && T.x<=s.B.x && s.A.y<=T.y && T.y<=s.B.y) 


* r比較 s.A.x<= T.x的esult然後比較 s.B.x

+0

我糾正它,但爲什麼printf的什麼都不做? – AndriusK

+1

@Atskalunas我的猜測是你沒有通過正確的價值觀。在調試器中設置'if'行,並檢查條件中使用的變量。 – dasblinkenlight

+0

以某封信爲例:A,B表示在當前上下文中找不到。 – AndriusK

1
  • 你缺少函數的返回類型

  • 你需要使用

    ((s.A.x <= T.x) && (T.x <= s.B.x) && (s.A.y <= T.y) && (T.y <= s.B.y)) 
    
  • 另一個問題來評價界限是: 在你函數的printf,你遞歸調用is_inside(A,B)。假設if條件變爲真,你將陷入無限循環。

    printf("Point (%f, %f)is inside rectangle \n", T.x, T.y); 
    
+1

@Atskalunas你需要打印你的觀點,而不是你遞歸地調用你的函數。 – bellati