首頁  >  文章  >  後端開發  >  中點線產生演算法的C++實現

中點線產生演算法的C++實現

王林
王林轉載
2023-09-09 19:49:101122瀏覽

中點線產生演算法的C++實現

一條線連接兩點。它是圖形中的基本元素。要繪製一條線,您需要兩個點,您可以在螢幕上在這兩個點之間繪製一條線,就圖形而言,我們將這些點稱為像素,每個像素都與整數座標相關聯。我們以 (x1, y1) 和 (x2, y2) 的形式給出整數座標,其中 x1

正在使用三種不同的演算法用於在螢幕上執行線生成,這些是-

  • DDA 演算法

  • Bresenham 線生成

  • 中點演算法

中點演算法

使用中點畫線的步驟點線演算法是-

  • 使用當前定位點計算中間點,即東(Xp 1,Yp)和東北(Xp 1,Yp) 1) 是中點(Xp 1, Yp 1/2)。

  • 現在,中點將決定螢幕上下一個座標的位置,即 p>

    • 如果中點在線上上方,則下一個座標將位於東邊。

    • 如果中間點在線下方,那麼下一個座標將在東北。

讓我們來看看各種輸入輸出場景這個-

#− int x_1 = 3,int y_1 = 3,int x_2 = 10,int y_2 = 8

輸出

輸出

strong>− 線產生演算法的中點為:3,3 4 ,4 5,5 6,5 7,6 8,7 9,7 10,8

說明− 我們給的座標為x_1 = 3, x_2 = 10, y_1 = 3, y_2 = 8。因此,步驟首先計算 dx = x_2 - x_1 作為 10 - 3 = 7 和 dy 作為 y_2 - y_1 8 - 3 = 5 且 然後檢查dy是否小於dx。現在將 d 計算為 5 - (7 / 2) = 2。第一個點為 x_1 和 y_1。列印它們。現在,當 x_1

輸入:int x_1 = 2, int y_1 = 2, int x_2 = 3, int y_2 = 4

輸出:透過線段生成演算法得到的中點為:2,2 3,3 3,4

解釋:給定座標為x_1 = 2, x_2 = 2, y_1 = 3, y_2 = 4。透過應用中點線段產生演算法,我們將計算出所有中點像素作為輸出。

下面程式所使用的方法如下:

  • 輸入整數點為int x_1, int y_1, int x_2, int y_2。呼叫函數Mid_Point(x_1, y_1, x_2, y_2)產生線段。

  • 在函數Mid_Point(x_1, y_1, x_2, y_2)內部

    • 計算dx為x_2 - x_1,dy為y_2 - y_1

    • 檢查IF dy小於或等於dx,則將d設為dy - (dx / 2),將first_pt設為x_1,將second_pt設為y_1

    • 印出first_pt和second_pt。

    • 開始while循環,當first_pt小於x_2時,增加first_pt 1,並檢查IF d小於0,則將d設為d dy,否則將d設為d (dy - dx),並將second_pt增加1。印出first_pt和second_pt。

    • 否則,如果dx小於dy,則將d設為dx - (dy/2),將first_pt設為x_1,將second_pt設為y_1,並列印first_pt和second_pt。

    • 開始while循環,當second_pt小於y_2時,在循環內部遞增second_pt second_pt加1。檢查IF d小於0,然後將d設定為d dx。否則,將d設為d (dx - dy),並將first_pt增加1。

    • 列印first_pt和second_pt。

範例

#include<bits/stdc++.h>
using namespace std;

void Mid_Point(int x_1, int y_1, int x_2, int y_2){
   int dx = x_2 - x_1;
   int dy = y_2 - y_1;

   if(dy <= dx){
      int d = dy - (dx / 2);
      int first_pt = x_1;
      int second_pt = y_1;

      cout<< first_pt << "," << second_pt << "\n";
      while(first_pt < x_2){
         first_pt++;
         if(d < 0){
            d = d + dy;
         }
         else{
            d = d + (dy - dx);
            second_pt++;
         }
            cout << first_pt << "," << second_pt << "\n";
      }
   }
   else if(dx < dy){
      int d = dx - (dy/2);
      int first_pt = x_1;
      int second_pt = y_1;
      cout << first_pt << "," << second_pt << "\n";
      while(second_pt < y_2){
         second_pt++;
         if(d < 0){
            d = d + dx;
         }
         else{
            d += (dx - dy);
            first_pt++;
         }
         cout << first_pt << "," << second_pt << "\n";
      }
   }
}
int main(){
   int x_1 = 3;
   int y_1 = 3;
   int x_2 = 10;
   int y_2 = 8;
   cout<<"Mid-Points through Line Generation Algorithm are: ";
   Mid_Point(x_1, y_1, x_2, y_2);
   return 0;
}

輸出

如果我們執行上面的程式碼,它將產生以下輸出

Mid-Points through Line Generation Algorithm are: 3,3
4,4
5,5
6,5
7,6
8,7
9,7
10,8

以上是中點線產生演算法的C++實現的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除