首頁> 後端開發> C++> 主體

連接3個點所需的水平或垂直線段的數量

WBOY
發布: 2023-08-25 16:49:12
轉載
728 人瀏覽過

連接3個點所需的水平或垂直線段的數量

假設給定三個不同的點(或座標),你想要找出透過連接這三個點可以形成的水平或垂直線段的數量。這樣的線段也稱為折線。為了解決這個問題,你需要計算幾何的概念。在本文中,我們將討論在C 中解決這個問題的各種方法。

輸入輸出場景

假設c1,c2和c3是笛卡爾平面上3個點的座標。連接這3個點的水平或垂直線段的數量將如下所示。

Input: c1 = (-1, -1), c2 = (-2, 3), c3 = (4, 3) Output: 1 Input: c1 = (1, -1), c2 = (1, 3), c3 = (4, 3) Output: 2 Input: c1 = (1, 1), c2 = (2, 6), c3 = (5, 2) Output: 3
登入後複製

注意− 水平和垂直線段必須與座標軸對齊。

使用 If 語句

我們可以使用 if 語句來檢查這三個點之間是否存在水平線或垂直線。

  • 建立一個函數,透過將c1.xc2.x、c1.xc3.xc2.x以及c3.x。如果滿足任意一個條件,則表示存在水平線段,且計數遞增。

  • 同樣,函數透過將c1.yc2.y、c1.yc3.yc2 .y以及c3.y。如果滿足任一條件,則表示垂直線段確實存在。數再次增加。

範例

#include  using namespace std; struct Coordinate { int x; int y; }; int countLineSegments(Coordinate c1, Coordinate c2, Coordinate c3) { int count = 0; // Check for the horizontal segment if (c1.x == c2.x || c1.x == c3.x || c2.x == c3.x) count++; // Check for the vertical segment if (c1.y == c2.y || c1.y == c3.y || c2.y == c3.y) count++; return count; } int main() { Coordinate c1, c2, c3; c1.x = -1; c1.y = -5; c2.x = -2; c2.y = 3; c3.x = 4; c3.y = 3; int numSegments = countLineSegments(c1, c2, c3); std::cout << "Number of horizontal or vertical line segments: " << numSegments << std::endl; return 0; }
登入後複製

輸出

Number of horizontal or vertical line segments: 1
登入後複製
登入後複製

注意如果所有三個點都在笛卡爾平面的同一軸上,即X 軸或Y 軸,則連接它們所需的線段數為1. 若點形成L形,則結果為2,否則結果為3。

使用輔助函數

  • 在這裡,我們可以使用輔助函數 (horizontalLineverticalLine) 來計算線段。

  • 我們利用這樣一個事實:在笛卡爾系統中,水平線的所有點都位於同一 y 座標上。horizontalLine函數透過比較兩個點的 y 座標來檢查它們是否可以形成水平線段。如果 y 座標相同,則存在水平線。

  • 類似地,垂直線的所有點都位於同一 x 座標上。verticalLine函數透過比較兩個點的x座標來檢查它們是否可以形成垂直線段。如果x座標相同,則存在垂直線。

  • 接下來,我們有countLineSegments函數,它用於計算水平和垂直線段的數量。如果存在水平或垂直線段,每次迭代後計數會增加。

範例

#include  using namespace std; struct Coordinate { int x; int y; }; // Helper functions bool horizontalLine(Coordinate c1, Coordinate c2) { return c1.y == c2.y; } bool verticalLine(Coordinate c1, Coordinate c2) { return c1.x == c2.x; } int countLineSegments(Coordinate c1, Coordinate c2, Coordinate c3) { int count = 0; // Check for horizontal segment if (horizontalLine(c1, c2) || horizontalLine(c1, c3) || horizontalLine(c2, c3)) count++; // Check for vertical segment if (verticalLine(c1, c2) || verticalLine(c1, c3) || verticalLine(c2, c3)) count++; return count; } int main() { Coordinate c1, c2, c3; c1.x = -1; c1.y = -5; c2.x = -2; c2.y = 3; c3.x = 4; c3.y = 3; int numSegments = countLineSegments(c1, c2, c3); std::cout << "Number of horizontal or vertical line segments: " << numSegments << std::endl; return 0; }
登入後複製

輸出

Number of horizontal or vertical line segments: 1
登入後複製
登入後複製

結論

在本文中,我們探索了使用 C 的各種方法來找出可以連接笛卡爾平面中 3 個不同點的水平線和垂直線的數量。我們已經討論了解決該問題的if語句方法。但由於迭代次數較多,時間複雜度也隨之增加。我們可以透過使用輔助函數來有效地解決這個問題,它減少了迭代次數,從而降低了時間複雜度。

以上是連接3個點所需的水平或垂直線段的數量的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!