根據妳的題目寫的
#include<iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
struct Pos
{
float xPos;
float yPos;
};
void PrintPos(std::vector<Pos> &PosVec)
{
for(int i=0;i<PosVec.size();++i)
{
cout<<"("<<PosVec[i].xPos<<","<<PosVec[i].yPos<<")"<<endl;
}
}
float GetXMin(std::vector<Pos> &PosVec)
{
float xMin;
xMin=PosVec[0].xPos;
for(int i=0;i<PosVec.size();++i)
{
if(xMin > PosVec[i].xPos)
{
xMin=PosVec[i].xPos;
}
}
return xMin;
}
float GetXMax(std::vector<Pos> &PosVec)
{
float xMax;
xMax=PosVec[0].xPos;
for(int i=0;i<PosVec.size();++i)
{
if(xMax < PosVec[i].xPos)
{
xMax=PosVec[i].xPos;
}
}
return xMax;
}
float Distance(std::vector<Pos> &PosVec,float xPos)
{
float SumDistance=0;
for(int i=0;i<PosVec.size();++i)
{
SumDistance+=((PosVec[i].xPos-xPos)*(PosVec[i].xPos-xPos)+(PosVec[i].yPos)*(PosVec[i].yPos));
}
return SumDistance;
}
int main()
{
std::vector<Pos> m_PosVec;
m_PosVec.clear();
string strInput;
string::size_type Index;
string strTmp;
char szTmp[128];
cout<<"讀取Input.txt文件..."<<endl;
ifstream ifs("Input.txt");
while(ifs>>strInput)
{
float x,y;
Index=strInput.find(",");
strTmp=strInput.substr(0,Index);
_snprintf(szTmp,sizeof(szTmp),"%s",strTmp.c_str());
sscanf(szTmp,"%f",&x);
strInput=strInput.substr(Index+1);
_snprintf(szTmp,sizeof(szTmp),"%s",strInput.c_str());
sscanf(szTmp,"%f",&y);
Pos m_Pos;
m_Pos.xPos=x;
m_Pos.yPos=y;
m_PosVec.push_back(m_Pos);
}
cout<<"Input.txt中的點如下:"<<endl;
PrintPos(m_PosVec);
cout<<"計算中..."<<endl<<endl;
float xMin,xMax;
xMin=GetXMin(m_PosVec);
xMax=GetXMax(m_PosVec);
float MinDistance=9999999;
float MinDisX;
for(float k=xMin;k<xMax;k+=0.1)
{
float TmpDistance=Distance(m_PosVec,k);
if(MinDistance>TmpDistance)
{
MinDistance=TmpDistance;
MinDisX=k;
}
}
cout<<"x軸上距所有點距離之和最短的點的坐標為"<<endl<<"("<<MinDisX<<",0)"<<endl;
system("pause");
return 0;
}
其中Input.txt中存放了點的坐標
運行結果如下