上週卡到暑輔考試
一直沒碰的Dog&Gopher
週末完成結果卡在pow()的用法上 compiler一直不給過...
昨天到學校待了一天 跟著老師Debug 修修補補之後才把原本的bug處理完...
重點是
後來才發現這題其實是不需要讀檔 用cin來寫就可以了(悲劇~~往好處想是多練習了一次開檔案處理???)
不過這段Code應該還可以更精簡...
原題:http://luckycat.kshs.kh.edu.tw/homework/q10310.htm
測資:下載
#include <iostream>
#include <stdlib.h>
#include <fstream>
#include <sstream>
#include <math.h>
using namespace std;
double Dog_X,Dog_Y,Gopher_X,Gopher_Y,Target_X,Target_Y;
string Temp_X,Temp_Y;
int CharToInt(char source)
{
int Num;
stringstream Temp;
Temp << source;
Temp >> Num;
return Num;
}
void GetLocation(string source)
{
int Counter = 1;
string Temp = "";
source = source + " ";
for(int i=2; i<source.length(); i++)
{
if(source[i] != ' ')
{
Temp = Temp + source[i];
}
else
{
if(Counter == 1)
{
Gopher_X = atof(Temp.c_str());
}
else if(Counter == 2)
{
Gopher_Y = atof(Temp.c_str());
}
else if(Counter == 3)
{
Dog_X = atof(Temp.c_str());
}
else if(Counter == 4)
{
Dog_Y = atof(Temp.c_str());
}
Temp = "";
Counter++;
}
}
}
bool Result(string source)
{
source = source + " ";
string Temp = "";
int Counter = 1;
for(int i=0; i<source.length(); i++)
{
if(source[i] != ' ')
{
Temp = Temp + source[i];
}
else
{
if(Counter == 1)
{
Temp_X = Temp;
Target_X = atof(Temp.c_str());
Counter++;
}
else if(Counter == 2)
{
Temp_Y = Temp;
Target_Y = atof(Temp.c_str());
}
Temp = "";
}
}
if((pow((Gopher_X-Target_X),2)+pow((Gopher_Y-Target_Y),2)) < ((pow((Dog_X-Target_X),2)+pow((Dog_Y-Target_Y),2))/4))
{
return true;
}
else
{
return false;
}
}
int main()
{
string FileLocateion;
string LineData = "";
bool Head = true; //判斷是否為測資首行
int N = 0; //測資洞口個數
ifstream infile("C:\\test.txt",ios::in);
if(infile)
{
while(!infile.eof())
{
getline(infile,LineData);
if (LineData.length()>1)
{
if(Head == true)
{
GetLocation(LineData); // Get Dog&Gopher Location
Head = false;
N = CharToInt(LineData[0]);
}
else
{
for (int i=0; i<N; i++)
{
if(Result(LineData) == true)
{
cout << "The gopher can escape through the hole at (" << Temp_X << "," << Temp_Y << ")" << endl;
break;
}
else
{
if(i == N-1)
{
cout << "The gopher cannot escape" << endl; //一直到測資最後一筆資料Gopher仍無法逃脫
}
}
LineData = "";
if (i<N-1)
{
getline(infile,LineData);
}
}
Head = true;
}
}
LineData = "";
}
}
else
{
cout << "Failded..." << endl;
}
return 0;
}
沒有留言:
張貼留言