OOP Assignment 2
#include <iostream>
#include <fstream>
using namespace std;
struct student {
char regno[9];
float gpa;
char name[10];
};
int main (){
ifstream datastream("studentsdata.txt");
if (!datastream) {
cerr<<"Error opening file"<<endl;
exit(-1);
}
int num = 0;
datastream >> num;
// allocate memory for num student objects
student * p = new student[num];
if (p==NULL) {
cerr<<"Error allocating memory"<<endl;
exit(-1);
}
for (int i=0; i<num; i++){
datastream >> p[i].regno >> p[i].gpa >> p[i].name;
}
int beststudent = 0;
float bestgpa = 0.0;
for (int i=0; i<num; i++){
if (p[i].gpa > bestgpa){
bestgpa = p[i].gpa;
beststudent = i;
}
}
cout << "The best student of class is:"<<endl;
cout << "Name: "<< p[beststudent].name << endl;
cout << "Regno: "<< p[beststudent].regno << endl;
cout << "gpa : "<< p[beststudent].gpa << endl;
return 0;
}
// from now onward its the second question
#include<iostream>
#include<cmath>
#include<fstream>
using namespace std;
struct point{
float x;
float y;
};
float disatace_cal(float a , float b , float c , float d){
return sqrt(pow((b - a), 2) + pow((d - c), 2));
};
int main(){
ifstream datastream("C:\\Users\\Administrator\\Downloads\\pointsdata.txt", ios::in);
if(!datastream){
cerr<<"fail to open file!"<<endl;
exit(-1);
}
int looper = 0;
datastream>>looper;
point *ptr = new point[looper];
if(!ptr){
cerr<<"fail to allocate dynamic memory!"<<endl;
exit(-1);
}
for(int i = 0; i < looper ; i++){
datastream>>ptr[i].x>>ptr[i].y;
}
float distances[5];
for(int i = 0 ; i < looper/2 ; i++){
distances[i] = disatace_cal(ptr[i+1].x , ptr[i].x , ptr[i+1].y , ptr[i].y);
}
for(int i=0; i <looper/2 ; i++){
cout<<distances[i]<<endl;
}
float result[3];
result[0] = distances[1] - distances[0];
for(int i = 0 ; i < 2 ; i++){
result[i+1] = distances[i+2] - distances[i+1];
}
float max =0;
for(int i =0 ; i < 2 ; i++){
if(max < result[i]){
max = result[i];
}
}
cout<<"The maximum difference is "<<max;
}
Comments
Post a Comment