【C/C++题目】输入三角形ABC的三个角坐标, 输出三角形ABC的面积

链接地址:【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. 如果对您有帮助可以点赞、收藏、关注,将会是我最大的动力 ↩︎

猜你喜欢

转载自www.cnblogs.com/CoutCodes/p/12930722.html