Using member function to solve equation C++ - c++

I am currently trying to create a program to calculate the mass of a rocket with given time values by passing an array to a member function of a class. I get these two errors and can't seem to figure out how to get rid of them. Any suggestions are much appreciated, thank you.
23 8 [Error] prototype for 'double equip::calcmass(double)' does not match any in class 'equip'
13 10 [Error] candidate is: double equip::calcmass()
#include <iostream>
#include <fstream>
#include <cmath>
#include <cstring>
using namespace std;
class equip
{
public:
double mass[999999999], velocity, height, time[999999999];
double calcmass();
private:
double T = 7000;
double g = 32.2;
double K = 0.008;
};
double equip::calcmass(double time)
{
int i = 0;
for(i=0; i=999999999; i++)
{
return mass[i] = (3000 - 40 * time[i]) / g;
}
}
int main()
{
int i = 0;
equip rocket;
ifstream infile;
string filename;
cout<<"Enter input file name for time (time): ";
cin>>filename;
infile.open(filename.c_str());
while(infile.fail())
{
cerr<<"Error opening file. \n";
cout<<"Enter file name: ";
cin>>filename;
infile.open(filename.c_str());
}
for(i=0; i<999999999; i++)
{
infile>>rocket.time[i];
}
for(i=0; i<999999999; i++)
{
cout<<rocket.mass[i];
}
return 0;
}

In your class definition you've declared
double calcmass()
In the definition of the member function it's
double calcmass(double time)
They do not match. One takes a double as argument and the other does not.

You were missing a bunch of headers, and in the function declaration was missing the parameter presents in the function definition:
#include <cmath>
#include <cstring>
#include <fstream>
#include<iostream>
using namespace std;
class equip
{
public:
...
double calcmass(double time); // here was missing the parameter
...
};
double equip::calcmass(double time)
{
...
}
Also you are doing time[i] on time which is a double, so you can't use operator[]... If you want to pass an array, you can use pointer to double:
class equip{
...
double calcmass(double* time)
}
double equip::calcmass(double* time)
{
...
}

Related

How to Define CountProbation() function using Functions from other Files?

I have been racking my brain on how to properly define the function CountProbation() properly in the Course.css file. I know that a for and if loop should probably be included but I am having trouble including functions from other files, even though I am including a header tag at the beginning of the current Course.css file.
Below are the C++ files that are given in the lab:
NOTE: Only the Course.cpp file is the one that needs to be edited. All of the other files are READ ONLY and purely for your information as the reader.
Sorry if it seems like a lot of code, but I didn't just want to include the Course.cpp file because then you might not understand the program.
Here are the compiler Errors/Warnings:
Course.cpp: In member function ‘int Course::CountProbation()’:
Course.cpp:8:18: warning: comparison of integer expressions of different signedness: ‘int’ and ‘std::vector<Student>::size_type’ {aka ‘long unsigned int’} [-Wsign-compare]
8 | for (int i=0; i < roster.size(); ++i) {
| ~~^~~~~~~~~~~~~~~
Course.cpp:9:9: error: ‘GetGPA’ was not declared in this scope
9 | if (GetGPA() < 2.0) {
| ^~~~~~
Course.cpp
#include <iostream>
#include "Course.h"
#include "Student.h"
using namespace std;
int Course::CountProbation() { //This is the function that I have tried to define as you can see by my
int probCount; //code
for (int i=1; i < roster.size(); ++i) {
if (GetGPA() < 2.0) {
probCount = probCount + 1;
}
}
return probCount;
}
void Course::AddStudent(Student s) {
roster.push_back(s);
}
Course.h (READ ONLY)
#ifndef COURSE_H
#define COURSE_H
#include <vector>
#include "Student.h"
class Course {
public:
int CountProbation();
void AddStudent(Student s);
private:
vector<Student> roster; //collection of Student objects
};
#endif
Main.cpp (READ ONLY)
#include <iostream>
#include <string>
#include "Course.h"
using namespace std;
int main() {
Course course;
int probCount;
// Example students for testing
course.AddStudent(Student("Henry", "Cabot", 3.2));
course.AddStudent(Student("Brenda", "Stern", 1.1));
course.AddStudent(Student("Lynda", "Robison", 2.4));
course.AddStudent(Student("Jane", "Flynn", 1.8));
probCount = course.CountProbation();
cout << "Probation count: " << probCount << endl;
return 0;
}
Student.h (READ ONLY)
#ifndef STUDENT_H
#define STUDENT_H
#include <string>
using namespace std;
// Class representing a student
class Student {
public:
Student(string first, string last, double gpa);
double GetGPA() ;
string GetLast();
private:
string first; // first name
string last; // last name
double gpa; // grade point average
};
#endif
Student.cpp (READ ONLY)
#include "Student.h"
// Student class constructor
Student::Student(string first, string last, double gpa) {
this->first = first; // first name
this->last = last; // last name
this->gpa = gpa; // grade point average
}
double Student::GetGPA() {
return gpa;
}
string Student::GetLast() {
return last;
}
This loop (as it was coded in the original question, before it was edited):
for (int i=1; i < roster.size(); ++i) {
if (Student.GetGPA() < 2.0) {
probCount = probCount + 1;
}
}
is flawed for three reasons:
i should start from 0, rather than 1
i should be of type size_t, rather than int
Student is a type, not a variable
A nice way to solve all these problems is to use a ranged for loop, like this:
for (Student &student : roster)
{
if (student.GetGPA() < 2.0)
probCount = probCount + 1;
}
As mentioned in the comments, you also need to initialise probCount to zero before entering the loop:
int probCount = 0;
Finally, it's worth noting that the above loop would normally be coded as:
for (const Student &student : roster)
{
...
but that won't work here as GetGPA is not declared as a const method. Thanks to #user4581301 for pointing this out.

Passing vector to member function of class

I am trying to pass a vector to a member function, but keep coming up with these errors:
27 28 [Error] 'double equip::calcmass' is not a static member of 'class equip'
13 19 [Error] invalid use of non-static data member 'equip::time'
27 24 [Error] from this location
28 1 [Error] expected unqualified-id before '{' token
How can I correct this?
#include <cmath>
#include <cstring>
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;
class equip
{
public:
vector <double> time;
vector <double> mass;
vector <double> velocity;
vector <double> height;
double calcmass();
double calcvelocity();
double calcheight();
double calctmax();
private:
double T = 7000;
double g = 32.2;
double K = 0.008;
};
double equip::calcmass(time);
{
int i = 0;
for(i=0; i<time.size(); i++)
{
return mass[i] = (3000 - 40 * time[i]) / g;
}
}
int main()
{
int i = 0;
ifstream infile;
string filename;
cout<<"Enter input file name for time (t): ";
cin>>filename;
infile.open(filename.c_str());
while(infile.fail())
{
cerr<<"Error opening file. \n";
cout<<"Enter file name: ";
cin>>filename;
infile.open(filename.c_str());
}
for(i=0; i<time.size(); i++)
{
infile>>time[i];
}
Your code is not working because you defined a a class equip, but never created an instance of it in main, and then you try to read a file content into a member of class time. Also, your function calcmass in the class definition has no arguments, but later you declare it with argument of undetermined type time. Remove the argument of a function, it will see time anyway as they are both members of the same class.

How to pass data through MVC for C++ (possibly using vectors or pointers)

So I have a project in which I must parse a data file, and dynamically create instances of a class Sensor while passing in the parsed data to that class. I am storing these instances in a vector of object pointers, sensors. Once the data is passed into each instance of Sensor, inside the Sensor class I must generate a reading value using the min and max values passed in from the parser. Then all of the values, min, max, type, reading, material, id must be passed to a controller class called SensorMount . This class is responsible for routing the data to a DisplayDeviceclass that I have not yet implemented.
I am confused on how to implement my controller SensorMount class. I know I need to use my get functions in the Sensor class, but I just am not sure where to start with this. Would another vector of Sensor object instances work? That is my current idea but I'm not sure if that is possible. I know sending a "message object" (Stated by my prof) could work but I can't seem to find any implementation of one online. I really appreciate any help and patience, I'm new to this and feel really stuck.
Also, I see alot of people on stack overflow condemn the use of using namespace but my professor wants us to use it. And we are not to implement a design pattern for this program (I know observer would work) , we will do that in the next.
Simulation.cpp (Where data parser is called and vector is created and initial data is passed )
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <stdio.h>
#include "Simulation.hpp"
#include "EnviroSimDataParser.h"
Simulation::Simulation() {}
Simulation::~Simulation(){}
void Simulation::initializeSimulation() {
char fileName[64];
char m_sType[64];
char m_sMaterial[64];
int m_iID;
char m_sUnits[64];
double m_sMinVal;
double m_sMaxVal;
char type[64];
int IDs[8];
int IDCount;
cout << "Enter the name of the data file:" << endl;
cin >> fileName ;
//cout << fileName << "\n" ;
parser = new EnviroSimDataParser(fileName);
for (int i = 0; i < 6; i++){
parser ->getSensorData(m_sType, m_sMaterial, &m_iID, m_sUnits, &m_sMinVal, &m_sMaxVal);
sensors.push_back(new Sensor(m_sType, m_sMaterial, m_iID, m_sUnits, m_sMinVal, m_sMaxVal));
cout << "success " << m_iID << endl;
}
for (int x = 0; x <4; x++){
parser -> getDisplayData(type, IDs, &IDCount);
//if (strcmp(type, ""))
}
mount = new SensorMount();
display = new Display();
}
void Simulation::runSimulation(){
}
Sensor.cpp
#include "Sensor.hpp"
Sensor::Sensor(char *SensorType, char *SensorMaterial, int SensorID, char *SensorUnit, double MaxVal, double MinVal) {
strcpy(type, SensorType);
strcpy(material, SensorMaterial);
ID = SensorID;
strcpy(unit, SensorUnit);
max = MaxVal;
min = MinVal;
}
Sensor::Sensor(){}
Sensor::~Sensor()
{
}
double Sensor::generateReading(){
reading = min + (rand() % (int)(max - min + 1));
cout << reading<< endl;
return reading;
}
char * Sensor::getType(){
return type;
}
char * Sensor::getMaterial(){
return material;
}
int Sensor::getID(){
return ID;
}
char * Sensor::getUnit(){
return unit;
}
double Sensor::getMin(){
return min;
}
double Sensor::getMax(){
return max;
}
double Sensor::getReading(){
return reading;
}
//void Sensor::sendSensorData(){
// SensorMount.routeData(Display)
//}
Sensor.h
#ifndef Sensor_hpp
#define Sensor_hpp
#include <stdio.h>
#include <iostream>
#include <fstream>
using namespace std;
class Sensor
{
public:
Sensor();
Sensor(char *SensorType, char *SensorMaterial, int SensorID, char *SensorUnit, double MaxVal, double MinVal);
~Sensor();
//virtual Sensor updateSensor();
char * getType();
char * getMaterial();
int getID();
char * getUnit();
double getMin();
double getMax();
double getReading();
private:
char type[32];
char material[32];
int ID;
int reading;
char unit[32];
double min;
double max;
double generateReading();
};
#endif /* Sensor_hpp */
SensorMount.h (controller)
#ifndef SensorMount_hpp
#define SensorMount_hpp
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <vector.
#include "Sensor.hpp"
#include "Display.hpp"
using namespace std;
class SensorMount{
private:
Sensor *sensors;
Display *displayDevices;
vectorgetSensorData;
public:
SensorMount();
~SensorMount();
};
#endif /* SensorMount_hpp */

Not declared in Scope

I have wrote a simple average calculation program trying to calculate a semester average. When I compile the code I get an error telling me my 'inputExam' function was not declared in this scope. I've researched the error message and I can't figure out what to do to fix it.
I also get this error for the other functions, but once I understand my error I think I can fix the others.
#include <iostream>
using namespace std;
int main()
{
double finalExam=0.0;
double midterm = 0.0;
double quizzes = 0.0;
double labs = 0.0;
double semGrade=0.0;
midterm=inputExam("Midterm");
finalExam=inputExam("Final");
quizzes=inputAndAvgQuizzes();
labs=inputAndAvgLabs();
semGrade=(midterm*.2)+(finalExam*.2)+(labs*.5)+(quizzes*.1);
cout<<"Your End of Semester Grade is: " semGrade;
return 0;
}
double inputExam(string examType)
{
double grade;
cout<< "Enter the " examType " Score: ";
cin>>grade;
return (grade);
}
double inputAndAvgLabs()
{
double num [4];
double sum;
double avg;
if (int a=0, a<3,a++)
{
cout<<"What is the grade?"<<endl;
cin>>num[a]>>endl;
}
if (int a=0, a<3, a++)
{
sum=sum+num[a];
}
avg=sum/4;
return avg;
}
double inputAndAvgQuizzes()
{
double num[3];
double sum;
double avg;
double lowest = num[0];
if (int a=0, a<2,a++)
{
cout<<"What is the grade?"<<endl;
cin>>num[a]>>endl;
}
if (lowest>num[1])
{
lowest=num[1];
}
if (lowest>num[2])
{
lowest=num[2];
}
sum=num[1]+num[2]+num[3]-lowest;
avg=sum/2;
return avg;
}
You need to let it be known that those functions exist so add prototypes for your functions above main or define your functions there. Like so:
...
double inputExam(string examType);
double inputAndAvgLabs();
double inputAndAvgQuizzes();
int main() { ... }
//definitions after main
..or copy paste all those definitions above the call to main like so:
...
// Function defs here
// Prototypes no longer needed
...
int main() {...}
// Defs no longer needed here
Alternatively you can put all the definitions in an external file and compile it into the project via a make file or better yet, and as you progress, create classes in header and implementation files and include them in your file the same way(sort of) that you do #include <iostream>.
Another small nugget of advice would be to avoid using namespace std;. If not only in theory it's bad practice and can lead to namespace clashing in larger projects. If you, like me, hate typing std::string ... then add using std::string; to your code for the same ease of use.
In C/C++ you need to declare the function before you use it. In this case, it simply means declaring function prototypes before your main function and then implementing them after the main function.
Example:
// declare a prototype
double Function(int variable);
int main()
{
Function(5);
return 0;
}
// Implement the function
double Function(int variable)
{
/* Do Something */
}
Alternatively, you could change your code to the form:
// Implement the function first
double Function(int variable)
{
/* Do Something */
}
int main()
{
Function("Testing");
return 0;
}

scope error message

Hey guys, just learning about composition of classes and ran into this error.
Gradebook.h
#ifndef GRADEBOOK_h
#define GRADEBOOK_h
#include "StudentRec.h"
#include <iostream>
#include <string>
class GradeBook
{
public:
GradeBook();
GradeBook(string initLastName, int studGrades);
void AddStudent(string initLastName, int studGrades);
void ShowStudents();
void UserInterface();
private:
static const int numStudents=20;
StudentRec student[numStudents];
static int studentCounter;
static int gradeCounter;
};
#endif
Gradebook.cpp
#include "Gradebook.h"
#include "StudentRec.h"
#include <iostream>
#include <string>
using namespace std;
GradeBook::GradeBook()
{}
GradeBook::GradeBook(string initLastName, int studGrades)
{}
void GradeBook::AddStudent(string initLastName, int studGrades)
{
gradeCounter++; //Increments variable responsible for tracking # of grades per student
StudentRec newStudent(initLastName, studGrades); //creates new student object
student[studentCounter]=newStudent; //Assigns new student object to array
studentCounter++; //Increments variable responsible for tracking # of students
}
void GradeBook::ShowStudents()
{
for(int i=0;i<studentCounter; i++){ //Displays information for each student instance
cout<<student[i].GetLastName()<<' ';
for(int j=0; j<gradeCounter; j++)
cout<<student[i].GetGrades(j)<<' ';
cout<<endl;
}
}
void GradeBook::UserInterface()
{
char choice=' ';
string studLastName;
int studGrade;
cout<<"Welcome to GradeBook, this program stores students"
<<" grades by last name. To ADD a student press the 'A'"
<<" key. To LIST all students, press the 'L' key. To "
<<" QUIT, press the 'Q' key."<<endl<<endl;
cin>>choice;
choice=toupper(choice);
while(choice!='Q')
{
if(choice='A'){
cout<<"To add a student, please enter their last name"
<<" followed by a space and a non-negative grade"
<<" Ex. McClure 96";
cin>>studLastName>>studGrade;
AddStudent(studLastName, studGrade);
}
else if(choice='L'){
cout<<"This is a list of all students in GradeBook"
<<endl<<endl;
ShowStudents(); //Displays all StudentRec objects
}
else if(choice!='Q')
cout<<"Please enter another letter"<<endl;
cout<<"To ADD a student press the 'A' key. To LIST all students, press the 'L' key. To "
<<" QUIT, press the 'Q' key."<<endl<<endl;
}
}
Main.cpp
#include <iostream>
#include <string>
#include "StudentRec.h"
#include "Gradebook.h"
using namespace std;
int main()
{
GradeBook gradeBook;
UserInterface();
return 0;
}
StudentRec.cpp
#include <iostream>
#include <string>
#include "StudentRec.h"
using namespace std;
StudentRec::StudentRec()
{
lastName=" ";
for(int i=0;i<numGrades; i++)
grades[i]=0;
}
StudentRec::StudentRec(string initLastName, int studGrade)
{
static int gradeCounter=0;
lastName=initLastName;
grades[gradeCounter]=studGrade;
}
string StudentRec::GetLastName()
{
return lastName;
}
int StudentRec::GetGrades(int gradeNum)
{
return grades[gradeNum];
}
void StudentRec::AddGrades(int studGrade)
{
gradeCounter++;
if(gradeCounter<=numGrades)
grades[gradeCounter]=studGrade;
else
cout<<"Too many grades for this student";
}
StudentRec.h
#ifndef STUDENTREC_h
#define STUDENTREC_h
#include <iostream>
#include <string>
using namespace std;
class StudentRec
{
public:
StudentRec();
StudentRec(string initLastName, int studGrade);
string GetLastName();
int GetGrades(int gradeNum);
void AddGrades(int studGrade);
private:
static const int numGrades=10;
static int gradeCounter;
string lastName;
int grades[numGrades];
};
#endif
In the Main.cpp file, I get an error I can't find the solution for. It reads
error: "UserInterface" was not declared in this scope. I got this error while compiling in XCode
I got error C3861: 'UserInterface': identifier not found
Obviously i've tried it in two IDEs, I also have the StudentRec.cpp and .h, but not sure you need them. Thanks in advance for the help
It appears that UserInterface() is actually a member function of GradeBook, correct?
If so, you need to add a declaration for the member function in the GradeBook class declaration:
class GradeBook
{
public:
GradeBook();
GradeBook(string initLastName, int studGrades);
void AddStudent(string initLastName, int studGrades);
void ShowStudents();
void UserInterface(); // Added
// ...
private:
// ...
};
This way, the compiler will "know" that the UserInterface() function exists as a member function. You then provided the definition in void GradeBook::UserInterface() in your .cpp file.
Then you need to call it on a GradeBook instance, like the gradeBook variable in your main() function:
int main()
{
GradeBook gradeBook;
// This calls the member function UserInterface() on the gradeBook variable.
gradeBook.UserInterface();
// This calls the global UserInterface(), which doesn't exist.
// UserInterface();
return 0;
}
UserInterface() is a method of GradeBook. The call probably needs to be:
gradeBook.UserInterface();