c++ class passing member function issues - c++

In class were learning about classes and structures, Im working on a program that is supposed to have to member functions in the class, one doing calculations and one to return certain values, it seems Im running into trouble calling the functions maybe? IM not a 100% sure because c++ cant specify the error. I hope you can help me, thank you in advance.
#include <iostream>
#include <cstdlib>
using namespace std;
void rocket(double massR,double massE, double massP,double avgTh,double bd);
double rocketreturn(double& MV,double& MA);
class Rocket
{
private:
double massR;
double massE;
double massP;
double avgTh; // average thrust
double bd; //burn duration
public:
void rocket(double massR,double massE, double massP,double avgTh,double bd)
{
massR=massR/1000;
massE=massE/1000;
massP=massP/1000;
double LM=massR+massE;
double MCP=massR+massE-massP;
double AM=(LM+MCP)/2;
double acc=(avgTh/AM)-9.8;
double MV= acc * bd;
double Alt=.5*acc*.5*.5;
double t=MV/9.8;
double MA=Alt+MV*t+.5*-9.8*t*t;
}
double rocketreturn(double& MV, double& MA)
{
cout<< MV;
cout<< MA;
}
};
int main( )
{
double massR; // mass of the rocket
double massE; // mass of the engine
double massP; // mass of the propellant
double avgTh; // average thrust
double bd; // burn duration
double MV; // max velocity
double MA; // max altitude
char ans;
system("CLS");
cout << "Take Home # by - "
<< "Rocket Object\n\n";
do
{
cout <<"Enter the mass of the rocket: "<<endl;
cin >> massR;
cout <<"Enter the mass of the engine: "<<endl;
cin >> massE;
cout <<"Enter the mass of the propellant: "<<endl;
cin >> massP;
cout <<"Enter the average thrust of the engine: "<<endl;
cin >> avgTh;
cout <<"Enter the burn duration of the engine: "<<endl;
cin >> bd;
rocketreturn(MV,MA);
cout <<"the rockets maximum velocity is " << MV<<endl;
cout <<"the rockets maximum altitude is "<<MA<<endl;
cout <<"Would you like to run the program again (Y or N)?"<<endl;
cin>>ans;
}
while(ans=='y'||ans=='Y');
}

You can try using the following program structure and fill in the details the way you wish. Note, it won't compile.
#include <iostream>
using namespace std;
class Rocket {
private:
double mR, mE;
public:
/* Constructor. It is missing in your program. You probably want it */
Rocket(double massR, double massE) {
/* Better to use initialization list, but this should work too */
mR = massR;
mE = massE;
}
double rocketreturn(double & a, double & b) {
/* Do sth with the parameters. But return a double,
which you are not doing in your program */
double result = a + b;
return result;
}
};
int main() {
double x, y;
do {
cin >> x >> y;
Rocket my_rocket(x, y);
double z = my_rocket.rocketreturn(x, y); // Assignment not necessary
} while ( /* some condition */) //my_rocket object will be destroyed after scope goes out
return 0;
}

Related

What am I doing wrong with this mortgage formula?

#include <iostream>
#include <cmath>
using namespace std;
/* FINDS AND INITIALIZES TERM */
void findTerm(int t) {
int term = t * 12;
}
/* FINDS AND INITIALIZES RATE */
void findRate(double r) {
double rate = r / 1200.0;
}
/* INITALIZES AMOUNT OF LOAN*/
void findAmount(int amount) {
int num1 = 0.0;
}
void findPayment(int amount, double rate, int term) {
int monthlyPayment = amount * rate / ( 1.0 -pow(rate + 1, -term));
cout<<"Your monthly payment is $"<<monthlyPayment<<". ";
}
This is the main function.
int main() {
int t, a, payment;
double r;
cout<<"Enter the amount of your mortage loan: \n ";
cin>>a;
cout<<"Enter the interest rate: \n";
cin>>r;
cout<<"Enter the term of your loan: \n";
cin>>t;
findPayment(a, r, t); // calls findPayment to calculate monthly payment.
return 0;
}
I ran it over and over again, but it still gives me the incorrect amount.
My professor gave us an example that goes like this:
Loan=$200,000
Rate=4.5%
Term: 30 years
And the findFormula() function is supposed to produce $1013.67 for the mortgage payment. My professor gave us that code as well (monthlyPayment = amount * rate / ( 1.0 – pow(rate + 1, -term));). I'm not sure what's wrong with my code.
The formula may be fine, but you are not returning, nor using, any value from your conversion functions, so its inputs are wrong.
Consider this refactoring of your program:
#include <iostream>
#include <iomanip> // for std::setprecision and std::fixed
#include <cmath>
namespace mortgage {
int months_from_years(int years) {
return years * 12;
}
double monthly_rate_from(double yearly_rate) {
return yearly_rate / 1200.0;
}
double monthly_payment(int amount, double yearly_rate, int years)
{
double rate = monthly_rate_from(yearly_rate);
int term = months_from_years(years);
return amount * rate / ( 1.0 - std::pow(rate + 1.0, -term));
}
} // end of namespace 'mortgage'
int main()
{
using std::cout;
using std::cin;
int amount;
cout << "Enter the amount of your mortage loan (dollars):\n";
cin >> amount;
double rate;
cout << "Enter the interest rate (percentage):\n";
cin >> rate;
int term_in_years;
cout << "Enter the term of your loan (years):\n";
cin >> term_in_years;
cout << "\nYour monthly payment is: $ " << std::setprecision(2) << std::fixed
<< mortgage::monthly_payment(amount, rate, term_in_years) << '\n';
}
It still lacks any checking of the user inputs, but given the values of your example, it outputs:
Enter the amount of your mortage loan (dollars):
200000
Enter the interest rate (percentage):
4.5
Enter the term of your loan (years):
30
Your monthly payment is: $ 1013.37
The slightly difference from your expected output (1013,67) could be due to any sort of rounding error, even a different overload of std::pow choosen by the compiler (since C++11, the integral parameters are promoted to double).

Why is my program giving weird results?

The following snippets are the header file and the actual main() function. I am using Visual Studio 2017 with Windows 10.
.h
#ifndef SALES_DATA_H
#define SALES_DATA_H
#include <iostream>
using namespace std;
struct Sales_data
{
int amount;
int rate;
int price = amount * rate;
};
#endif
.cpp
#include <iostream>
#include "Sales_data.h"
using namespace std;
int main()
{
Sales_data item1;
cout << "Enter rate and amount" << endl;
cin >> item1.rate >> item1.amount;
cout << item1.price << endl;
cin.get();
cin.get();
return 0;
}
It keeps showing this as the output: "687194768".
I also tried initializing the variables but it does not seem to work.
What you probably want is:
struct Sales_data
{
int amount = 0;
int rate = 0;
int price() const { return amount * rate; }
};
And then
std::in >> item1.rate >> item1.amount;
std::cout << item1.price() << std::endl;
Price here is being calculated only at initialisation time to get its initial value, however since amount and rate have not been initialised yet, the result is undefined.
It is not a function.
struct Sales_data
{
int amount;
int rate;
int price = amount * rate;
};
You most likely wanted a function, e.g.:
struct Sales_data
{
int amount;
int rate;
int calcPrice()
{
return = amount * rate;
}
};
std::cout << item1.calcPrice() << std::endl;
Or you would have to refactor to initialise amount and rate to make use of such syntax, e.g. with a constructor.
struct Sales_data
{
int amount;
int rate;
int price = amount * rate;
Sales_data(int amount, int rate) : amount(amount), rate(rate) {}
};
Sales_data x(10, 5);
//x.price == 50
the reason the code is printing that is because you are calculating that price with uninitialized variables...
define a function in the struct and call it after the input is given
void calculatePrice() {
price = amount * rate;
}
cin >> item1.rate >> item1.amount;
item1.calculatePrice();
cout << item1.price << endl;
As others have commented, your definition for Sales_data uses amount or rate before they were ever initialised. This is undefined behaviour, and your compiler is more or less free to do whatever it pleases with this.
Many compilers will initialise variables with some sort of recognisable guard value (a popular choice is 0xDEADBEEF) as a way to make it quite obvious when a value is uninitialised when looking at it with a debugger. In this case, it looks like your compiler uses 0xCCCCCCCC as that guard value:
(lldb) p (int) 0xcccccccc * (int) 0xcccccccc
(int) $2 = 687194768

Having issues with void function

I'm trying to the program to display the bonus, but the programs renders an answer to 0. I am extremely new to c++ so any guidance would be greatly appreciated.
Here's the code:
#include <iostream>
#include <iomanip>
using namespace std;
//function prototypes
void enterItems(double, double);
void calcAndDisplayBonus(double &salesAmt, double &rate);
int main()
{
//declare variables
double sales = 0.0;
double bonusRate = 0.0;
//enter input values
enterItems(sales, bonusRate);
//calculate and display bonus
cout << fixed << setprecision(2);
calcAndDisplayBonus(sales, bonusRate);
system("pause");
return 0;
} //end of main function
//*****function definitions*****
void enterItems(double salesAmt, double rate)
{
cout << "Enter sales: ";
cin >> salesAmt;
cout << "Enter bonus rate (in decimal form): ";
cin >> rate;
} //end of enterItems function
void calcAndDisplayBonus(double &salesAmt, double &rate)
{
cout << "Bonus: $" << salesAmt * rate << endl;
} //end of calcAndDisplayBonus function
When you call enterItems, you are passing parameters by copy. This means that your changes won't affect the variables available in the scope of the caller.
To solve it, you can either pass a couple of references or pointers, as well as rely on a pair returned from the function as a result, and so on.
As an example, by writing:
void enterItems(double &salesAmt, double &rate)
You'll actually solve the problem above mentioned.
Another valid prototype is:
void enterItems(double *salesAmt, double *rate)
Even though this one asks for a small set of changes all around your code (the example, of course).
There is a plenty of possible solutions, hoping these ones will give you an idea of what's wrong.
Your function
void enterItems(double salesAmt, double rate)
is taking two double-parameters by value, this means, your changes you do inside the function will not be visible from the outside. You could take the doubles by reference:
void enterItems(double &salesAmt, double &rate)
but i'd prefer to return the values, but since you can only return a single value you'd need two functions:
double enterSales()
{
double tmp;
cout << "Enter sales: ";
cin >> tmp;
return tmp;
}
double enterBonus()
{
double tmp;
cout << "Enter bonus rate (in decimal form): ";
cin >> tmp;
return tmp;
}
//in your main:
double sales = enterSales();
double bonusRate = enterBonus();

C++ object oriented problems [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
This is an assignment i am trying to figure out:
Create a new project named Project3 and create a class named Rover
Within the Rover class, specify the following member instance variables:
name(string)
x position on a grid (integer)
y position on a grid (integer)
direction by compass – N, S, E, or W (String)
speed (0 – 5 meters per second, integer)
Within the Rover class, specify the following methods:
Default constructor – set the rover’s position to (0,0), its speed to 0, its direction to
North.
Constructor that receives parameters to initialize all five instance variables described above
Setter methods for each instance variable
Getter methods for each instance variable
getRoverData – returns a string that displays values for each instance variable of the
current rover object, placing each value on a separate line, as follows:
Rover name: A
X-position: 0
Y-position: 0
Direction: E
Speed: 1
Create a class client (main) that creates an array of the a maximum of five rovers and gets the initial
values for all rovers from the user. After the user specifies values for each rover, display a summary
of the rover’s values as shown above.
I have about a billion errors and i dont know why.
using namespace std;
class Rover {
private:
string name;
int x;
int y;
string direction;
int speed;
int position[10][10];
public:
void Rover();
void constructor(string name, int x, int y, string direction, int speed);
void setName(string name);
void setX(int x);
void setY(int y);
void setDirection(string direction);
void setSpeed();
string getName();
int getX();
int getY();
string getDirection();
int getSpeed();
string getRoverData();
};
void Rover::Rover() {
r1.position[0][0];
r1.speed = 0;
r1.direction = "N";
}
string Rover::getRoverData() {
cout << "Rover name: " << r1.getName() << endl;
cout << "X-position: " << r1.getX() << endl;
cout << "Y-position: " << r1.getY() << endl;
cout << "Direction: " << r1.getDirection() << endl;
cout << "Speed: " << r1.getSpeed() << endl;
}
void Rover::constructor(string name1, int x1, int y1, string direction1, int speed1) {
r1.name = name1;
r1.x = x1;
r1.y = y1;
r1.direction = direction1;
r1.speed = speed1;
}
void Rover::setName(string name) {
r1.name = name;
}
void Rover::setX(int x) {
r1.x = x;
}
void Rover::setY(int y) {
r1.y = y;
}
void Rover::setDirection(string direction) {
r1.direction = direction;
}
void Rover::setSpeed(int speed) {
r1.speed = speed;
}
string Rover::getName() {
return name;
}
int Rover::getX() {
return x;
}
int Rover::getY() {
return y;
}
string Rover::getDirection() {
return direction;
}
int Rover::getSpeed() {
return speed;
}
int main(int argc, char** argv) {
string name;
int x;
int y;
string direction;
int speed;
Rover r1;
r1.constructor("Yoda", 3, 3, "N", 3);
cout << "Enter name for Rover: ";
cin >> name;
r1.setName(name);
cout << "Enter its x position: ";
cin >> x;
r1.setX(x);
cout << "Enter its y position: ";
cin >> y;
r1.setY(y);
cout << "Enter direction N,E,S,W: ";
cin >> direction;
r1.setDirection(direction);
cout << "Enter its speed: ";
cin >> speed;
r1.setSpeed(speed);
r1.getRoverData();
return 0;
}
Your example appears incomplete. I'm guessing you just missed including the following lines in your post
#include <string>
#include <iostream>
using namespace std;
First, constructors do not have a return type so void Rover(); makes no sense. Remove void and you're golden there.
Second, what exactly do you think r1 is supposed to be? The compiler should tell you the identifier is undefined because it isn't. remove r1. from your member functions (i.e. anything function starting with Rover::. and you're golden there.
Third, what do you think r1.position[0][0] is going to do? It's just an expression that does nothing. Even position[0][0] is not going to do anything. Perhaps you want to initialize the array somehow but you haven't provided enough information to determine what you're trying to accomplish with it.
Fourth, the member function void Rover::setSpeed(int) has not been declared within the Rover class. Did you forget something? Based on your code it should be
int Rover::getSpeed()
{
return speed;
}
Fifth, void Rover::setSpeed(); doesn't make much sense unless it actually accepts an argument.

Separate classes into separate files in C++

EDIT: Added the "addition" class in, accidentally forgot about it.
How do I separate classes into different files? I understand how classes work and how to make objects and things like that. However, I'm finding some confusion in the process of putting classes in different files. Thanks much for any help! Also, I am using CodeBlocks as an IDE. Here is my understanding so far:
Create new class, and CB gives you a ".h" and a new ".cpp".
The "Classname::Classname" at the beginning of the source file is a Scope Resolution Operator.
You use "#include classname.h" in your main source file to import its contents.
You can call functions from "main" by using the objects that you have declared.
This is my understanding so far, but I'm just confused on how to implement it. I have created a simple calculator with all the classes in one source file. It works fine, and I guess I'm pretty proud of it :) I know there is a lot easier way to make something like this, but I used classes and objects instead for the sole purpose of practice. Here's my code for the calculator. Also, I really apologize for the long post :/ Thanks, if you have come this far in reading it, and thanks especially if you can help me out a bit!
Here's my code in one source file:
#include <iostream>
using namespace std;
class Addition {
public:
float add (float x, float y) {
float sum;
sum=x+y;
return sum;
}
};
class Subtraction {
public:
float subtract (float x, float y) {
float dif;
dif=x-y;
return dif;
}
};
class Multiplication {
public:
float multiply (float x, float y) {
float prod;
prod=x*y;
return prod;
}
};
class Division {
public:
float divide (float x, float y) {
float quot;
quot=x/y;
return quot;
}
};
int op;
char cont;
int main()
{
do {
cout<<"Welcome to C++ Calculator v2!"<<endl;
cout<<"Select the number for which operation you want to use: "<<endl;
cout<<"1-Addition"<<endl;
cout<<"2-Subtraction"<<endl;
cout<<"3-Mutliplication"<<endl;
cout<<"4-Division"<<endl;
cin>>op;
if (op==1) {
float num1;
float num2;
Addition addobj;
cout<<"You have chosen Addition!"<<endl;
cout<<"Enter the first number you want to add: "<<endl;
cin>>num1;
cout<<"Enter the second number you wat to add: "<<endl;
cin>>num2;
float ans=addobj.add(num1, num2);
cout<<"The sum is "<<ans<<endl;
cout<<"Do you wish to continue? Y/N"<<endl;
cin>>cont;
}
if (op==2) {
float num1;
float num2;
Subtraction subobj;
cout<<"You have chosen Subtraction!"<<endl;
cout<<"Enter the first number you want to subtract: "<<endl;
cin>>num1;
cout<<"Enter the second number you want to subtract: "<<endl;
cin>>num2;
float ans=subobj.subtract(num1, num2);
cout<<"The difference is "<<ans<<endl;
cout<<"Do you wish to continue? Y/N"<<endl;
cin>>cont;
}
if (op==3) {
float num1;
float num2;
Multiplication multobj;
cout<<"You have chosen Multiplication!"<<endl;
cout<<"Enter the first number you want to multiply: "<<endl;
cin>>num1;
cout<<"Enter the second number you want to multiply: "<<endl;
cin>>num2;
float ans=multobj.multiply(num1, num2);
cout<<"The product is "<<ans<<endl;
cout<<"Do you wish to continue? Y/N"<<endl;
cin>>cont;
}
if (op==4) {
float num1;
float num2;
Division divobj;
cout<<"You have chosen Division!"<<endl;
cout<<"Enter the first number you want to divide: "<<endl;
cin>>num1;
cout<<"Enter the second number you want to divide: "<<endl;
cin>>num2;
float ans=divobj.divide(num1, num2);
cout<<"The quotient is "<<ans<<endl;
cout<<"Do you wish to continue? Y/N"<<endl;
cin>>cont;
}
} while (cont=='Y'||cont=='y');
if (cont=='N'||'n') {
cout<<"Thanks for using my program, goodbye!"<<endl;
}
return 0;
}
Ok, I will show you by doing your example:
subtraction.h
class Subtraction
{
public:
float subtract (float x, float y);
};
subtraction.cxx
#include "subtraction.h"
float Subtraction::subtract (float x, float y)
{
float dif;
dif=x-y;
return dif;
}
multiplication.h
class Multiplication
{
public:
float multiply (float x, float y);
};
multiplication.cxx
#include "multiplication.h"
float Multiplication::multiply (float x, float y)
{
float prod;
prod=x*y;
return prod;
}
and so on...
main.cxx
#include "subtraction.h"
#include "multiplication.h"
int main()
{
//use the classes just as before.
}
Also, I didn't put it in the code here, for simplicity, but go ahead and get into the habit of ensuring that your declarations are only included once. On a large project, this can get very nasty if you don't put these safeguards in.
#ifndef SUBTRACTION_H
#define SUBTRACTION_H
class Subtraction
{
....
};
#endif /*SUBTRACTION_H*/
here's something like Jonathan's example (I did not add the include guards for brevity, definitely do so though!), but with some duplication removed and some OO added for your learning pleasure. Note that while this is certainly not how an actual calculator would be implemented, it will hopefully give you some more understanding of C++ if you study it well enough.
mathoperation.h:
//a base class!
class MathOperation
{
public:
virtual float doit( float x, float y ) const = 0;
};
subrtaction.h:
class Subtraction : public MathOperation
{
public:
float doit( float x, float y ) const;
};
addition.h:
class Addition : public MathOperation
{
public:
float doit( float x, float y ) const;
};
subtraction.cpp:
#include "subtraction.h"
float Subtraction::doit( float x, float y ) const { return x - y; }
addition.cpp:
#include "addition.h"
float Subtraction::doit( float x, float y ) const { return x + y; }
main.cpp:
#include <iostream>
#include <string>
//yes this saves typing, but there reasons not to use it.. search SO!
using namespace std;
//this one avoids you having to copy/paste the similar parts
void DoIt( const MathOperation& op, const std::string& opName, const std::string& verb, const std::string& resultName )
{
cout << "You have chosen " << opName << "!" << endl;
cout<<"Enter the first number you want to " << verb << ": "<< endl;
//here you should actually check if the user really types in a number, and not "blablabla"
//and off course, put it in a seperate function so you can reuse it for num2
float num1;
cin>>num1;
float num2;
cout<<"Enter the second number you wat to " << verb << ": "<< endl;
cin>>num2;
cout<<"The " << resultName << " is " << op.doit( num1, num2 ) <<endl;
}
int main()
{
int op;
char cont = 'n';
do {
cout<<"Welcome to C++ Calculator v2!"<<endl;
cout<<"Select the number for which operation you want to use: "<<endl;
cout<<"1-Addition"<<endl;
cout<<"2-Subtraction"<<endl;
cout<<"3-Mutliplication"<<endl;
cout<<"4-Division"<<endl;
cin>>op;
//see how much shorter this is?
if( op == 1 )
DoIt( Addition(), "Addition", "add", "sum" );
else if (op==2)
DoIt( Subtraction(), "Subtraction", "subtract", "difference" );
else
cout << "Sorry I don't know this number" << endl;
cout<<"Do you wish to continue? Y/N"<<endl;
cin>>cont;
} while (cont=='Y'||cont=='y');
cout<<"Thanks for using my program, goodbye!"<<endl;
return 0;
}
It's good to name your files the same way as the class. It's not such a good idea in your case, beacause your classes are short, but each class should have its own 2 files - for example Subtraction.h and Subtraction.cpp. In the .h file you should put only the decaration - in your case:
class Subtraction
{
public:
float subtract (float , float);
}
In the .cpp file you should include the .h file and put the implementation. In your case:
float Substraction::subtract (float x, float y)
{
float dif;
dif=x-y;
return dif;
}
See also C++ Header Files, Code Separation and Why have header files and .cpp files in C++?
Hope this helps a bit! :)
It's good to have only one public class per file.
By convention filename is the same as the classname (with an extension like .h .hh or .hpp if some definitions are done in the file).
if you want to put different classes in different files, a simple text editor will help you to do that.