إيجاد ميل خطٍّ مستقيم

من موسوعة حسوب
اذهب إلى التنقل اذهب إلى البحث
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

تحسب هذه الخوارزمية مقدار ميل الخطّ المستقيم.

مثال:

Input  : x1 = 4, y1 = 2, 
         x2 = 2, y2 = 5 
Output : Slope is -1.5

مبدأ عمل الخوارزمية

تتطلب عملية حساب ميل خطّ مستقيم إلى اختيار نقطتين من الخطّ ولتكونا (x1, y1) و (x2, y2).

تستخدم هذه المعادلة لحساب الميل من النقاط المعطاة.

تنفيذ الخوارزمية

  • C++‎:
#include <bits/stdc++.h> 
using namespace std; 

float slope(float x1, float y1, float x2, float y2) 
{ 
	return (y2 - y1) / (x2 - x1); 
} 

// اختبار الدالة السابقة
int main() 
{ 
	float x1 = 4, y1 = 2; 
	float x2 = 2, y2 = 5; 
	cout << "Slope is: "
		<< slope(x1, y1, x2, y2); 
	return 0; 
}
  • بايثون:
def slope(x1, y1, x2, y2): 
	return (float)(y2-y1)/(x2-x1) 

# اختبار الدالة السابقة
x1 = 4
y1 = 2
x2 = 2
y2 = 5
print "Slope is :", slope(x1, y1, x2, y2)
  • جافا:
import java.io.*; 

class GFG { 
	static float slope(float x1, float y1, 
					float x2, float y2) 
	{ 
		return (y2 - y1) / (x2 - x1); 
	} 

    // اختبار التابع السابق
    public static void main(String[] args) 
	{ 
		float x1 = 4, y1 = 2; 
		float x2 = 2, y2 = 5; 
		System.out.println("Slope is " + 
					slope(x1, y1, x2, y2)); 
	} 
}

تعطي الشيفرات السابقة المخرجات التالية:

Slope is: -1.5

مصادر