【C/C++題目】輸入三角形ABC的三個角座標, 輸出三角形ABC的面積

利用海倫公式求三角形面積,因此先利用兩點距離公式求得邊長,即可求出面積

一、實現代碼

#include <iostream>
#include <cmath>
using namespace std;

int transform(char* str, int* coord);	//提取數字函數
double length(int* a, int* b);			//計算邊長函數

int main()
{
	char str[10];                           //輸入的字符串
	int coord1[2], coord2[2], coord3[2];    //儲存三個座標值
	int judge;
	for (int i = 0; i < 3; i++)
	{
		cout << "座標" << i << ":";
		gets_s(str);

		switch (i + 1)
		{
		case 1:
			judge = transform(str, coord1);
			break;
		case 2:
			judge = transform(str, coord2);
			break;
		case 3:
			judge = transform(str, coord3);
			break;
		}

		if (judge != 2)                   //輸入的座標不是兩個數字
		{
			cout << "座標中必須只有兩個數字組成!" << endl;
			i--;		//重新輸入
		}
	}
	cout << "三個座標分別爲:(" << coord1[0] << "," << coord1[1] << "),(" << coord2[0] << "," << coord2[1] << "),(" << coord3[0] << "," << coord3[1] << ")" << endl;;

	double p, a, b, c;  //半周長,三邊長度
	double s;           //面積

	a = length(coord1, coord2);
	b = length(coord3, coord2);
	c = length(coord1, coord3);
	p = (a + b + c) / 2;

	cout << "三邊長度:" << a << "," << b << "," << c << endl;

	s = sqrt(p * (p - a) * (p - b) * (p - c));      //海倫公式

	cout << "面積:" << s << endl;;
	return 0;
}

int transform(char* str, int* coord)    //提取數字
{
	int count = 0;          //0-x;1-y

	for (int i = 0; i < 10; i++)		
	{
		while (str[i] && (str[i] < '0' || str[i] > '9'))       //跳過非數字部分
			i++;

		if (str[i])
		{
			coord[count] = str[i] - '0';                      //字符轉換

			if (str[i + 1] >= '0' && str[i + 1] <= '9')			//判斷後一位
			{
				coord[count] = coord[count] * 10 + str[i + 1] - '0';		//數字累和
				i++;		//往後挪1
			}
			count++;
		}
		else               //字符爲空
			break;
	}
	return count;
}

double length(int* a, int* b)      //計算邊長
{
	int subx, suby;
	double len;

	subx = abs(a[0] - b[0]);    //x座標之差的絕對值
	suby = abs(a[1] - b[1]);    //y座標之差的絕對值

	len = sqrt(pow(subx, 2) + pow(suby, 2));     //兩點距離公式,得邊長

	return len;
}

二、運行效果

在這裏插入圖片描述

如有不足之處,還望指正 1


  1. 如果對您有幫助可以點贊、收藏、關注,將會是我最大的動力 ↩︎

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章