如果您對數學上合理的比較感興趣,您不應該直接比較任意unsigned
和signed ints
。那是因爲C(++)的算術不是你常規的數學算術。
在涉及signed int
和unsigned int
一個C(++)的表達,所述signed int
首先被轉換爲一個unsigned int
,然後執行操作(+,*,<,等)。
要正確比較signed int
和unsigned int
,您應該考慮C(++)的「算術規則」以及編程語言規定的並且對於未初始化者不可見的類型/值轉換。
所以,你可以比較兩個這樣的:
/* returns -1 if s < u,
returns 0 if s == u,
returns 1 if s > u */
int CompareSignedUnsigned(int s, unsigned u)
{
if (s < 0) return -1; // negative is always smaller than 0 or positive
if (s < u) return -1; // obvious
if (s > u) return 1; // obvious
return 0; // obvious
}
至於使用正確的整數,這是一個很好的建議,但有時一個尺寸不適合所有。而屏幕上的座標就是這樣一個區域,在這個區域裏簽署座標可能更合理。例如,想象一下,你想要一個例程在屏幕上渲染一個盒子,並且你希望能夠畫出一個在屏幕上移動的盒子,從屏幕外部移動(移動到屏幕外部)並在外部結束(搬出去)。
如果你選擇這樣的API:
void DrawBox(unsigned x, unsigned y, unsigned width, unsigned height, color c);
這一功能的用戶將不得不做繪圖盒的一部分時,一些額外的數學,當一個部分是在屏幕上,另一個是關閉屏幕。所有這些都是因爲根本沒有辦法告訴這個功能,原來的/未被收縮的盒子確實不在屏幕上。
現在,如果你選擇這一項,而不是:
void DrawBox(int x, int y, unsigned width, unsigned height, color c);
和移動額外的裁剪數學函數裏面,突然這個功能的用戶能夠編寫代碼非常簡單。它可以是這樣簡單:
for (int x = -100; x < SCREEN_WIDTH + 100, x++)
DrawBox(x, SCREEN_HEIGHT/2, 100, 50, GREEN);
謝謝,我會給頂部一個鏡頭(或類似的東西)。我不認爲會有一個「好」的出路。再次感謝! – Cramer 2012-08-19 06:35:41