这是头文件
#pragma once
#include <vector>
#include <string>
using namespace std;
class CLASSIFIER
{
public:
double x, y, z;
string orientation;
public:
CLASSIFIER(double x = 0.0, double y = 0.0, double z = 0.0, string orientation = "") {
this->x = x;
this->y = y;
this->z = z;
this->orientation = orientation;
}
double getX() {
return x;
}
double getY() {
return y;
}
double getz() {
return y;
}
string getorientation() {
return orientation;
}
};
void printDummyClassifier();
void printKNNClassifier();
double euclideanDistance(const CLASSIFIER& c1, const CLASSIFIER& c2);
string nearestNeighbor(const CLASSIFIER& classifier, const vector<CLASSIFIER>& trainingData);
这是cpp文件
#include "CLASSIFIER.h"
#include <iostream>
#include <limits>
#include <cmath>
using namespace std;
void printDummyClassifier() {
cout << "DummyClassifier is not implemented yet" << endl;
}
void printKNNClassifier() {
cout << "printKNNClassifier is not implemented yet" << endl;
}
double euclideanDistance(const CLASSIFIER& c1, const CLASSIFIER& c2) {
double dx = c1.x - c2.x;
double dy = c1.y - c2.y;
double dz = c1.z - c2.z;
return sqrt(dx * dx + dy * dy + dz * dz);
}
string nearestNeighbor(const CLASSIFIER& classifier, const vector<CLASSIFIER>& trainingData) {
string orientation;
double minDistance = numeric_limits<double>::max();
for (const CLASSIFIER& c : trainingData) {
double distance = euclideanDistance(classifier, c);
if (distance < minDistance) {
minDistance = distance;
orientation = c.orientation;
}
}
return orientation;
}
这是main文件
#include <iostream>
#include<fstream>
#include <string>
#include <vector>
#include"CLASSIFIER.h"
using namespace std;
int main() {
vector<CLASSIFIER> trainingData;
ifstream file("trainingData.txt");
if (!file.is_open()) {
cerr << "Error: Could not open file" << endl;
return 1;
}
double x, y, z;
string orientation;
while (file >> x >> y >> z >> orientation) {
CLASSIFIER classifier = { x, y, z, orientation };
trainingData.push_back(classifier);
}
file.close();
cout << "Choose a classifier: " << endl;
cout << "1. DummyClassifier" << endl;
cout << "2. Nearest Neighbor (NN) Classifier" << endl;
cout << "3. k-NN Classifier" << endl;
int choice;
cin >> choice;
if (choice == 1) {
printDummyClassifier();
}
else if (choice == 2) {
cout << "Enter data (x, y, z): ";
double x, y, z;
cin >> x >> y >> z;
CLASSIFIER classifier = { x, y, z };
string orientation = nearestNeighbor(classifier, trainingData);
cout << "The phone orientation is: " << orientation << endl;
if (z < 0)
{
cout << "face up";
}
if (z > 0)
{
cout << "face down";
}
if (y < 0)
{
cout << "face portrail";
}
if (y > 0)
{
cout << "portrail upside down";
}
if (x < 0)
{
cout << "landscope left";
}
if (x > 0)
{
cout << "landscope right";
}
}
else if (choice == 3) {
printKNNClassifier();
}
else {
cout << "Invalid choice" << endl;
}
return 0;
}
这是要求