Okay so i created program that simulates a landscaping company and so we have to calculate the cost of Sod and fence. So when i enter in both the length and width they out put huge decimals for example
Parkton Landscaping
Enter Length: 10
Enter width: 12
Lanscaping Costs
Sod = 6871947680.00
Fence = 19327352760.00
Press any key to continue . . .
Sod is suppose to = 56.40
and Fence is suppose to = 990.00
please help here is my code and both files
#include <iostream>
#include <iomanip>
using namespace std;
#include "c:\Users\barta\OneDrive\Documents\Visual Studio 2015\Projects\Project 6\Project 6\Geometry.h"
#include "Pricing.h"
int main()
{
int length, width;
Pricing landscape;
Geometry geo;
const double Fenceprice = 22.50;
const double Sodprice = .47;
cout << "\t Parkton Landscaping " << endl;
cout << "Enter Length: ";
cin >> length;
cout << "Enter width: ";
cin >> width;
//Pricing(length, width);
//geo.getLength();
//geo.getWidth();
std::cout << std::fixed << std::setprecision(2);
landscape.displayOutput();
cout << "Sod = " << landscape.getsodCost(length) << endl;
cout << "Fence = " << landscape.getFenceCost(Fenceprice) << endl;
system("pause");
return 0;
}
here is the header file:
#pragma once
class Geometry
{//an object is how you access the class
public:// where the public function definitions are created
Geometry();// Default Constructor
Geometry(int, int);
Geometry(int);
void setLength(int); //assigns length
void setWidth(int); //assigns width
void setSide(int); //assigns side
//Constructor function that recieves the values for the rectangle
//Constructor function that recieves values for the cube
int getLength(),
getWidth(),
getSide(),
getArea(),
getPerimeter(),
getSurfaceArea();
private: //where the private members are created
int length,
width,
side;
void checkNum(int); //function that checks to see if the number is less than 0
};
Geometry::Geometry()
{
length = length;
width = width;
side = 0;
}
Geometry:: Geometry(int length, int width) /*function recieves 2 intergers and calls checkNum to validate if */
{
setLength(length);
setWidth(width);
checkNum(length);
checkNum(width);
}
Geometry:: Geometry(int sides)
{
checkNum(sides);
setSide(sides);
}
int Geometry::getLength()
{
return length;
}
int Geometry::getWidth()
{
return width;
}
int Geometry::getSide()
{
return side;
}
int Geometry::getArea()
{
return length * width;
}
int Geometry::getPerimeter()
{
return 2 * (length + width);
}
int Geometry::getSurfaceArea()
{
return 6 * (side * side);
}
void Geometry::setLength(int len)
{
length = len;
checkNum(len);
}
void Geometry::setWidth(int widths)
{
width = widths;
checkNum(widths);
}
void Geometry::setSide(int s)
{
side = s;
checkNum(s);
}
void Geometry::checkNum(int num) //function checks to see if the number is less than zero
{
if (num <= 0)
{
cout << "!!!!!!!!WARNING!!!!!! this isnt a number" << " program will now exit......" << endl;
system("pause");
exit(1);
}
}
Header file #2
#include "Geometry.h"
class Pricing : Geometry
{
public:
Pricing();
Pricing(int length, int width);
double getsodCost(double);
double getFenceCost(double);
void displayOutput();
private:
};
Pricing::Pricing(int length, int width) :Geometry(length, width)
{
}
Pricing::Pricing()
{
}
double Pricing::getsodCost(double price)
{
getArea();
return getArea()*price;
}
double Pricing::getFenceCost(double price)
{
getPerimeter();
return getPerimeter()*price;
}
void Pricing::displayOutput()
{
cout << "\n\n";
cout << "\t Lanscaping Costs " << endl;
}
Because you never initialize the objects with valid values, meaning Geometry::width and Geogrpapy::length are uninitialized and have indeterminate values. Using them uninitialized leads to undefined behavior.
Related
I'm new to programming, I have been reading Sams Teach Yourself C++ in 24 hours. I just started learning classes and am confused on how to allow user input on private data. I created the following class that returns the area of a Trapezoid. Any suggestions would be greatly appreciated.
class Trapezoid
{
//assigns a number to a variable
private:
int a = 20;
int b = 25;
int height = 30;
int area;
public:
int getArea();
};
int Trapezoid::getArea()
{
// calculates the area and returns it.
area = (a + b) / 2 + height;
return area;
}
#include "AreaTrapezoid.hpp"
#include <iostream>
int main()
{
// accesses area inside the Trapeziod class.
Trapezoid areaT;
areaT.getArea();
// displays the area result
std::cout << "The area of a Trapezoid: " << areaT.getArea() << std::endl;
std::cout << system("pause");
return 0;
}
You need to read the user's input, and then expose public access to assign new values to the class's private members. For example:
class Trapezoid
{
//assigns a number to a variable
private:
int a = 20;
int b = 25;
int height = 30;
public:
int getArea();
void setA(int value);
void setB(int value);
void setHeight(int value);
};
int Trapezoid::getArea()
{
// calculates the area and returns it.
return (a + b) / 2 + height;
}
void Trapezoid::setA(int value)
{
a = value;
}
void Trapezoid::setB(int value);
{
b = value;
}
void Trapezoid::setHeight(int value)
{
height = value;
}
#include <iostream>
#include <limits>
#include <cstdlib>
#include "AreaTrapezoid.hpp"
int main()
{
Trapezoid areaT;
int value;
// get the user's input and apply it to the Trapeziod.
std::cout << "Enter A: ";
std::cin >> value;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
areaT.setA(value);
std::cout << "Enter B: ";
std::cin >> value;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
areaT.setB(value);
std::cout << "Enter Height: ";
std::cin >> value;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
areaT.setHeight(value);
// displays the area result
std::cout << "The area of the Trapezoid: " << areaT.getArea() << std::endl;
std::system("pause");
return 0;
}
Alternatively, use a constructor instead:
class Trapezoid
{
//assigns a number to a variable
private:
int a;
int b;
int height;
public:
Trapezoid(int a, int b, int height);
int getArea();
};
Trapezoid::Trapezoid(int a, int b, int height)
: a(a), b(b), height(height)
{
}
int Trapezoid::getArea()
{
// calculates the area and returns it.
return (a + b) / 2 + height;
}
#include <iostream>
#include <limits>
#include <cstdlib>
#include "AreaTrapezoid.hpp"
int main()
{
int a, b, h;
// get the user's input and apply it to the Trapeziod.
std::cout << "Enter A: ";
std::cin >> a;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Enter B: ";
std::cin >> b;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
areaT.setB(value);
std::cout << "Enter Height: ";
std::cin >> h;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// displays the area result
Trapezoid areaT(a, b, h);
std::cout << "The area of the Trapezoid: " << areaT.getArea() << std::endl;
std::system("pause");
return 0;
}
Hi all, I am having some trouble with the below assignment. When I run the code, everything appears to work, but the numbers that I get in the print out are not accurate. Not sure if it is the constructor I have that is set up wrong or what. I've just been banging my head against the wall trying to figure it out. Any help/advice would be much appreciated!
Here is the assignment text:
Car Class Instructions: Write a class named 'Car' that has the following member variables:
year. An int that holds the car's model year.
make. A string object that holds the make of the car.
speed. An int object that holds the car's current speed.
In addition, the class should have the following member functions:
Constructor. The constructor should accept the car's year and make member variables. The constructor should initialize these values to the object's year and make member variables. The constructor should initialize the speed member variable to 0.
Accessors. Appropriate accessor functions should be created to allow values to be retrieved from an object's year, make and speed member variables.
Accelerate. The accelerate function should add 5 to the speed member variable each time it is called.
Brake. THe brake function should subtract 5 from the speed member variable each time it is called. Demonstrate the class in a program that creates a Car object, and then calls the accelerate function five times. After each call to the accelerate function, get the current speed of the car and display it. Then, call the brake function 5 times. After each call to the brake function, get the current speed of the car and display it.
#include <iostream>
#include <string>
using namespace std;
class Car
{
private:
int year;
string make;
int speed;
public:
Car(int, string, int);
int getSpeed();
int getModel();
void accelerate();
void brake();
};
int Car::getSpeed()
{
return speed;
}
Car::Car(int year, string make, int speed = 0 )
{
}
void Car::accelerate()
{
speed +=5;
}
void Car::brake()
{
if( speed > 5 )
speed -=5;
else speed = 0 ;
}
int main ()
{
int year;
string make;
cout << "Please enter the model year of the car.\n";
cin >> year ;
cout << "Please enter the make of the car.\n";
cin >> make ;
Car myCar(year,make);
int i = 0;
for (; i<5; ++i)
{
myCar.accelerate();
cout << "Accelerating.\n" << "The current speed of the car is: " << myCar.getSpeed()<<endl;
}
{
int j = 0;
for (; j<5; ++j)
{
myCar.brake();
cout << "Decelerating.\n" << "The current speed of the car is: " << myCar.getSpeed()<<endl;
}
return (0);
}
}
This constructor
Car::Car(int year, string make, int speed = 0 )
{
}
initialize nothing. It has an empty body and neither initializer member list. Moreover according to the assignment the constructor has to have two parameters.
It can look the following way
Inside the class definition
inline Car( int year, std::string & make );
and the definition of the constructor itself
Car::Car( int year, const std::string make ) : year( year ), make( make ), speed( 0 )
{
}
The accessors can be declared like
int getYear() const;
int getSpeed() const;
const std::string & getModel() const;
^^^^^^^^^^^^^^^^^^^
The constructor
Car::Car(int year, string make, int speed = 0 )
{
}
is not doing what you describe. The three parameters (year, make, and speed) have the same names as Cars members, but are separate variables.
The result is that Cars members are default constructed, and the values passed by main() are effectively ignored.
To make things clearer, give the arguments different names, and initialise the members in an initialiser list.
Car::Car(int y, string m, int s) : year(y), make(m), speed(s)
{
}
It is permissible for the arguments to have the same names as class members, but this tends to be harder to read i.e. it is easier to misunderstand what the code is doing. In your case, you believe that giving the parameters the same name as class members serves to initialise the class members, and that is flat-out wrong. Either way, the constructor needs to explicitly initialise the members using the parameters, otherwise the class members receive default values (not the ones passed).
Also, if you want an argument with a default value, specify it in the definition of the class, not in the definition of the constructor. For example;
class Car
{
public:
Car(int, std::string, int = 0);
};
Car::Car(int y, string m, int s) : year(y), make(m), speed(s)
{
}
That makes things easier, particularly if the class definition is in a header file.
#include "stdafx.h"
#include <iomanip>
#include <iostream>
#include<stdio.h>
#include <cstdlib>
#include <string>
#include <iomanip>
double getaccelarate(double &, double &);
double getbrake(double &, double &);
double getcruise(double &, double &);
void outputStatusHeader();
void demo();
double updateDistanceTraveled(double &, double &);
int delta = 5;
//double brakee = 0;
double previousSpeed = 0;
double currentSpeed = 0;
using namespace std;
int main()
{
char command;
//The amount of elapsed time for each calculation interval
(fixed at 1 second)
const int timeInterval = 1;
//double currentSpeed=0;
//convert into the distance travelled by feet
int totalFeetTraveled = 0;
//the average speed travel
int averageSpeed = 0;
//double previousSpeed =0;
int averageSpeed_FeetPerSecond = 0;
int intervalFeetTraveled = 0;
int speed = 0;
//the amount of time that the time will increase by
//const int delta= 5;
while (true)
{
cout << "Command:";
cin >> command;
switch (command)
{
case 'a':
//double accelarate;
double speed;
speed = getaccelarate(currentSpeed, previousSpeed);
//cout << getaccelarate;
cout << "Accelerate"<<setw(20)<<"Accelerating"<<setw(5);
cout << speed;
double conve;
conve = updateDistanceTraveled(previousSpeed,
currentSpeed);
cout <<setw(10)<<setprecision(3)<<conve<<endl;
//updateDistanceTraveled(previousSpeed,currentSpeed);
break;
case 'b':
double brake;
brake = getbrake(previousSpeed, currentSpeed);
cout << "Brake" <<setw(20)<<"Braking"<<setw(5);
cout << brake;
//double brake1 = 0;
//brake1 = updateDistanceTraveled(previousSpeed,
currentSpeed);
cout << setw(10) << setprecision(3) << conve << endl;
break;
case 'c':
double cruise;
cruise = getcruise(previousSpeed, currentSpeed);
cout << "Cruise" << setw(20) << "Cruising" << setw(5);
cout << cruise;
cout << setw(10) << setprecision(3) << conve << endl;
break;
case 'h':
outputStatusHeader();
break;
case 'd':
demo();
break;
case 'q':
cout << " Exit program";
exit(1);
break;
default:
cout << "Invalid command" << endl;
break;
}
}
system("pause");
return 0;
}
//converting mph to feet perhours
double updateDistanceTraveled(double &previousSpeed,double ¤tSpeed)
{
//getaccelarate(previousSpeed, currentSpeed);
double averageSpeed = 0;
double averageSpeed_FeetPerSecond = 0;
double intervalFeetTraveled=0;
//double totalFeetTraveled=0;
const int timeInterval = 1;
averageSpeed = (previousSpeed + currentSpeed) / 2;
averageSpeed_FeetPerSecond = averageSpeed * 5280.0 / 3600.0;
intervalFeetTraveled = averageSpeed_FeetPerSecond * timeInterval;
return intervalFeetTraveled;
/*totalFeetTraveled = totalFeetTraveled + intervalFeetTraveled;
return totalFeetTraveled;*/
}
//to decrease speed
double getbrake(double &previousSpeed, double ¤tSpeed)
{
previousSpeed = currentSpeed;
currentSpeed -= delta;
return currentSpeed;
}
//to increase speed
double getaccelarate(double &previousSpeed, double ¤tSpeed)
{
previousSpeed = currentSpeed;
currentSpeed = currentSpeed + delta;
return currentSpeed;
}
// to stay in current speed
double getcruise(double &previousSpeed, double ¤tSpeed)
{
previousSpeed = currentSpeed;
return previousSpeed;
}
//unfinished demo
void demo()
{
cout << "Function Current State Current Speed Interval Distance
Total Feet (and miles) traveled" << endl;
cout << "-----------------------------------------------------------------------------------" << endl;
for (int x = 1; x < 4; x++)
{
double speed;
speed = getaccelarate(currentSpeed, previousSpeed);
//cout << getaccelarate;
cout << "Accelerate" << setw(20) << "Accelerating" << setw(5);
cout << speed;
double conve;
conve = updateDistanceTraveled(previousSpeed, currentSpeed);
cout << setw(10) << setprecision(3) << conve << endl;
}
}
//for supported commands
void outputStatusHeader()
{
cout << " supported commands\n"
<< " a accelerate\n"
<< " b brake\n"
<< " c cruise\n"
<< " d demo\n"
<< " h print this help text\n"
<< " q quit(end the program)"
<< endl;
}
{
cout << " supported commands\n"
<< " a accelerate\n"
<< " b brake\n"
<< " c cruise\n"
<< " d demo\n"
<< " h print this help text\n"
<< " q quit(end the program)"
<< endl;
}
This question already has answers here:
How to Calculate Execution Time of a Code Snippet in C++
(18 answers)
Closed 8 years ago.
I have a snowball launcher game codes. There is a arm to launch snowball and the target in the game. I have 2 different block of codes that makes the calculation for releasing angle of the arm with the input of length of the arm and target's x and y coordinates. One of them is:
#include <iostream>
#include <cmath> // math library
#include <windows.h> // system()
using namespace std;
class SnowballMachine{
private:
double L,X,Y, theta; //L for Lenght of the arm, X and Y is the coordinates
const double pi = 3.14159265; //Theta=Release angle
public:
void input() //get inputs for lenght of the arm and coordinates
{
cout<<"Please enter the coordinations of the target(for Target(x,y) enter 40 28)" <<endl;
cin>>X>>Y;
cout<<"Please enter the length of the arm: "<<endl;
cin>>L;
}
double calculate(){ //calculates the release angle with perpendicular slope comparison
if(L*Y <= X*sqrt(pow(Y, 2.0)+pow(X, 2.0)-pow(L, 2.0)))
{
theta=asin((L*Y + X*sqrt(pow(Y, 2.0)+pow(X, 2.0)-pow(L, 2.0)))/(pow(Y, 2.0)+pow(X, 2.0)));
return theta;
}
else
{
theta=asin((L*Y - X*sqrt(pow(Y, 2.0)+pow(X, 2.0)-pow(L, 2.0)))/(pow(Y,2.0)+pow(X, 2.0)));
return theta;
}
}
void ThetaDisplay() //displays output
{
cout << "The releasing angle is "<<180-(theta*180/pi)<<" degrees"<<endl;
}
};
//const values for options to get input
const int OPEN_GATE=1 ;
const int LOAD_SNOWBALL = 2;
const int ADJUST_ARM=3;
const int RELEASE_ARM=4;
const int QUIT=5;
int menu(); // get a command
void execute(int, SnowballMachine &Dummy); // run a given command
int main()
{
SnowballMachine A; //calling the class
A.input(); //calling the functions
A.calculate();
int choice;
A.ThetaDisplay();
do //select the options
{
choice = menu();
execute(choice, A);
} while (choice != QUIT );*/
return 0;
}
int select;
system("cls");
do
{
cout <<"1....Open the gate\n";
cout <<"2....Load the Snowball\n";
cout <<"3...Adjust the arm\n";
cout <<"4....Release the Snowball\n";
cout<<"5...Quit\n";
cout <<"enter selection: ";
cin >> select;
} while (select!=1 && select!=2 && select!=3 && select!=4 &&select!=5);
return select;
}
void execute(int cmd, SnowballMachine &Dummy)
{
//options switch method
switch (cmd)
{
case OPEN_GATE: cout << "Opening the gate\n";
break;
case LOAD_SNOWBALL: cout << "Loading the snowball\n";
break;
case ADJUST_ARM:cout<<"Adjusting the arm\n";
break;
case RELEASE_ARM:cout<<"Releasing the arm\n";
Dummy.calculate();
Dummy.ThetaDisplay();
break;
case QUIT:cout<<"Quitting!!!";
break;
default:
cout <<" Invalid Entry. Try it again please.";
}
This is the first one. Second one is:
This is the main.cpp
#include <iostream>
#include "Snowball.h"
using namespace std;
int main()
{
Snowball A;
A.Display();
A.ArmLength();
A.Input();
A.SetStartPOS();
for(double i = A.getLength(); i>A.getStartPOS(); i-=A.DELTAX)
{
if (A.Derivative(A, i)*.9999 >= ((A.getY()-A.foo(i))/(A.getX()-i))*1.0001)
{
A.setxPointcirc(i);
break;
}
}
A.AngleDisplay();
return 0;
}
This is the part of main.cpp which is snowball.cpp which calls all the functions:
#include "Snowball.h"
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
void Snowball::Input()
{
cout << "Enter the x-postion of the target: ";
cin >> x;
while(x < armlength || x < armlength*-1)
{
cout << endl;
cout << "Please make sure your x is greater than " << armlength << '.' << endl;
cout << "Enter the x-postion of the target. ";
cin >> x;
}
cout << "Enter the y-postion of the target: ";
cin >> y;
while(y < 0 || (y < armlength && x<armlength) )
{
cout << endl;
cout << "Enter the y-postion of the target: ";
cin >> y;
}
this->x =x;
this->y =y;
}
void Snowball::ArmLength()
{
cout << "Enter the Length of the Arm: ";
cin >> armlength;
this->armlength =armlength;
}
void Snowball::Display()
{
cout << "Welcome to the Snowball Launcher. \n\n";
}
double Snowball::foo(double x)
{
double z;
z = sqrt(powf(armlength, 2.0)-powf(x, 2.0));
return z;
}
double Snowball::Derivative(Snowball &foo_dummy, double x)
{
return (foo_dummy.foo(x+DELTAX/2.0) - foo_dummy.foo(x-DELTAX/2))/DELTAX;
}
void Snowball::AngleDisplay()
{
theta = rad2deg(acos(xPointCircle/armlength));
cout << "\nTarget Destroyed.\nAngle Required is: " << theta << " degrees." << setprecision(4) <<endl;
}
void Snowball::SetStartPOS()
{
StartPOS = armlength*-1;
}
void Snowball::setxPointcirc(double i)
{
xPointCircle = i;
}
And here is the getters and setters with declaring the const and variables header:
#ifndef SNOWBALL_H_INCLUDED
#define SNOWBALL_H_INCLUDED
#include <iostream>
#include <cmath>
using namespace std;
class Snowball {
private:
double rad2deg(double h) {return h*(180/pi); };
double x, y, theta, xPointCircle, StartPOS, armlength;
public:
static const double pi = 3.1415926535897;
static const double DELTAX = 0.001;
double foo(double x);
double Derivative(Snowball &foo_dummy, double x);
void Display();
void Input();
double getLength() {return armlength; }
double getStartPOS() {return StartPOS; }
double getY() {return y; }
double getX() {return x; }
void setxPointcirc(double i);
void ArmLength();
void AngleDisplay();
void SetStartPOS();
};
#endif
Here is my question: I get the same results with both 2 different block of codes. I want to
test which execution time is less(which one would be faster?).
Generally the way this is approached is to call the function n number of times (for large n) and calculate the time taken across the calls.
For instance, call it "the first way" 100000 times (getting the time before and time after) then calculate it "the second way" the same number of times (again checking the time before and after). By subtracting the two, you'll get a decent estimate of which is faster/slower.
Note that you need to test it many numbers of times to get an accurate result, not just once!
//I want to use 3 functions here with 1 struct that one function do the input
and one for calculation and the other one for out put but
I don't know how to reference //the variables in functions rec2 and rec3. I want to do it without using pointer
struct rectangle {
float length;
float width;
float area,perimeter;
};
rectangle rec1();
rectangle rec2();
rectangle rec3();
int main(){
rectangle f;
f = rec1();
f=rec2();
f = rec3();
return 0;
}
rectangle rec1(){
rectangle h;
cout<<"insert the length: ";
cin>>h.length;
cout<<"\ninsert width: ";
cin>>h.width;
return h;
}
rectangle rec2(){
rectangle z;
z.area=z.length*z.width;
z.perimeter=2*(z.length+z.width);
return z;
}
rectangle rec3(){
rectangle x;
cout<<"\narea is: "<<x.area<<endl<<"perimeter is: "<<x.perimeter<<endl;
return x;
}
You need to add methods to your rectangle struct.
struct rectangle
{
float length, width, area, perimeter;
void Input()
{
cout << "insert the length: ";
cin >> length;
cout << "\ninsert width: ";
cin>> width;
}
void Process(); // etc
void Output(); // etc
};
// Create a rectangle object and call it's methods
int main()
{
rectangle r;
r.Input();
r.Process();
r.Output()
}
The methods can now reference the member variables of the struct.
I suggest you change your design.
Place the input, process and output functions as methods inside the rectangle structure.
Placing the functions inside the structure allows them to access the data members.
Every time you return a new rectangle and assign it to your f variable, you are overwriting all of f's members, not just the ones you modified inside the function. You need to change the functions to modify f directly instead. You don't have to use a pointer for that, you can use a reference instead:
struct rectangle {
float length;
float width;
float area, perimeter;
};
void rec1(rectangle&);
void rec2(rectangle&);
void rec3(rectangle&);
int main(){
rectangle f;
rec1(f);
rec2(f);
rec3(f);
return 0;
}
void rec1(rectangle &r){
cout << "insert the length: ";
cin >> r.length;
cout << endl << "insert width: ";
cin >> r.width;
}
void rec2(rectangle &r){
r.area = r.length * r.width;
r.perimeter = 2 * (r.length + r.width);
}
void rec3(rectangle &r){
cout << endl << "area is: " << r.area << endl << "perimeter is: " << r.perimeter << endl;
}
But, this is C++ we are talking about, afterall. Member methods are your friends :)
struct rectangle {
float length;
float width;
float area, perimeter;
void rec1();
void rec2();
void rec3();
};
void rectangle::rec1(){
cout << "insert the length: ";
cin >> length;
cout << endl << "insert width: ";
cin >> width;
}
void rectangle::rec2(){
area = length * width;
perimeter = 2 * (length + width);
}
void rectangle::rec3(){
cout << endl << "area is: " << area << endl << "perimeter is: " << perimeter << endl;
}
int main(){
rectangle f;
f.rec1();
f.rec2();
f.rec3();
return 0;
}
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
So here is my code:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Point
{
private:
double px;
double py;
public:
void setX(const double x);
void setY(const double y);
double getX() const;
double getY() const;
};
class Rectangle
{
private:
string name;
Point blPoint;
double length, height;
public:
// member functions
void setName(const string & inName);
void setBottomLeft(const double x, const double y);
void setDimensions(const double inLength, const double inHeight);
string getName() const;
Point getBottomLeft() const;
double getLength() const;
double getHeight() const;
double area() const;
double perimeter() const;
Point midPoint() const;
void scaleBy2();
void display() const;
};
// FUNCTION PROTOTYPES GO HERE:
void welcome();
bool read_rec(const string promptName, const string errorInvalid, const string errorUsed, string & inName, vector<Rectangle> & list);
void read_coord(const string promptPoint, double & x, double & y);
void read_length(const string promptLength, double & inLength, double & inHeight);
void add_rec(const string Name, double x, double y, double inLength, double inHeight, vector<Rectangle> & list);
int main()
{
// Define your local variables, e.g. a vector of class Rectangle
Rectangle rec;
vector<Rectangle> list;
string prompt1stName = "Enter the name of the first rectangle: ";
string promptName = "Enter the name of the next rectangle: ";
string errorInvalid = "Invalid input. Type 'rec' following by the name or 'stop' if done.";
string errorUsed = "This name is already being used!";
string inName;
string Name;
// Display welcome banner
welcome();
/* Prompt user for first rectangle or 'stop' */
bool read = read_rec(prompt1stName, errorInvalid, errorUsed, inName, list);
// WHILE user input is invalid
while (read == false)
{
// Display "Try again! "
cout << "Try again! " << endl;
read = read_rec(prompt1stName, errorInvalid, errorUsed, inName, list);
}
// IF user input is not 'stop'
if (inName != "stop")
{
// Extract rectangle name from user input
int a = inName.length() - 4;
Name = inName.substr(4, a);
// Prompt for bottom left point
double x, y;
string promptPoint = "Enter " + Name + "'s bottom left x and y coords: ";
read_coord(promptPoint, x, y);
// Prompt for length and height
double inLength, inHeight;
string promptLength = "Enter " + Name + "'s length and height: ";
read_length(promptLength, inLength, inHeight);
// Add rectangle to the rectangle list
add_rec(Name, x, y, inLength, inHeight, list);
}
/* Prompt user for next rectangle or 'stop' */
// WHILE user input not 'stop'
while (inName != "stop")
{
// Display "Thank you! "
cout << "Thank you! ";
bool read = read_rec(promptName, errorInvalid, errorUsed, inName, list);
// WHILE user input is invalid while (read == false)
{
// Display "Try again! "
cout << "Try again! " << endl;
read = read_rec(promptName, errorInvalid, errorUsed, inName, list);
}
// IF user input is not 'stop'
if (inName != "stop")
{
// Extract rectangle name from user input
int a = inName.length() - 4;
Name = inName.substr(4, a);
// Prompt for bottom left point
double x, y;
string promptPoint = "Enter " + Name + "'s bottom left x and y coords: ";
read_coord(promptPoint, x, y);
// Prompt for length and height
double inLength, inHeight;
string promptLength = "Enter " + Name + "'s length and height: ";
read_length(promptLength, inLength, inHeight);
// Add rectangle to the rectangle list
add_rec(Name, x, y, inLength, inHeight, list);
}
}
// IF the rectangle list is not empty
if (list.size() != 0)
{
// Display all rectangles in the rectangle list
int rec_num = 0;
int i = 1;
while (i< list.size())
{
rec_num++;
i++;
}
cout << "You have " << rec_num+1 << " rectangle(s) in your list: ";
cout << endl;
for (int i = 0; i < list.size(); i++)
{
cout << "Rectangle '" << list[i].getName() << "' : ";
list[i].display();
list[i].scaleBy2();
cout << " After scale by 2: ";
list[i].display();
cout << endl;
}
}
// ELSE
else
{
// Display that no rectangles are in the list
cout << "You have no rectangles in your list." << endl;
}
return 0;
}
// FUNCTION DEFINITIONS GO HERE:
void welcome()
{
cout << "Welcome! Create your own list of rectangles." << endl;
cout << "You will be asked to provide information about each rectangle in your list by name." << endl;
cout << "Type the word 'stop' for the rectangle name when you are done." << endl;
cout << endl;
}
bool read_rec(const string promptName, const string errorInvalid, const string errorUsed, string & inName, vector<Rectangle> & list)
{
cout << promptName;
getline(cin, inName);
if (inName == "stop")
{
return(true);
}
else if (inName.substr(0,4) != "rec ")
{
cout << errorInvalid;
return(false);
}
else
{
int j = 0;
for (int i = 0; i < list.size(); i++)
{
if (inName == "rec " + list[i].getName())
{
j = j+1;
}
}
if (j == 0)
{
return(true);
}
if (j != 0)
{
cout << errorUsed;
return(false);
}
}
}
void read_coord(const string promptPoint, double & x, double & y)
{
cout << promptPoint;
cin >> x;
cin >> y;
}
void read_length(const string promptLength, double & inLength, double & inHeight)
{
cout << promptLength;
cin >> inLength;
cin >> inHeight;
cout << endl;
while (inLength <= 0 || inHeight <= 0)
{
cout << "Make length and height positive values. Try again.";
cout << promptLength;
cin >> inLength;
cin >> inHeight;
cout << endl;
}
}
void add_rec(const string Name, double x, double y, double inLength, double inHeight, vector<Rectangle> & list)
{
Rectangle rec;
rec.setName(Name);
rec.setBottomLeft(x, y);
rec.setDimensions(inLength, inHeight);
list.push_back(rec);
}
// CLASS MEMBER FUNCTION DEFINITINOS GO HERE:
void Point::setX(const double x)
{
px = x;
}
void Point::setY(const double y)
{
py = y;
}
double Point::getX() const
{
return (px);
}
double Point::getY() const
{
return (py);
}
void Rectangle::setName(const string & inName)
{
name = inName;
}
void Rectangle::setBottomLeft(const double x, const double y)
{
blPoint.setX(x);
blPoint.setY(y);
}
void Rectangle::setDimensions(const double inLength, const double inHeight)
{
length = inLength;
height = inHeight;
}
string Rectangle::getName() const
{
return (name);
}
Point Rectangle::getBottomLeft() const
{
return (blPoint);
}
double Rectangle::getLength() const
{
return (length);
}
double Rectangle::getHeight() const
{
return (height);
}
double Rectangle::area() const
{
// area = length * height
return(length * height);
}
double Rectangle::perimeter() const
{
// perimeter = 2 * (length + height);
return(2 * (length + height));
}
Point Rectangle::midPoint() const
{
Point midPoint;
double mx = blPoint.getX() + 0.5 * length;
double my = blPoint.getY() + 0.5 * height;
midPoint.setX(mx);
midPoint.setY(my);
return(midPoint);
}
void Rectangle::scaleBy2()
{
double midx = blPoint.getX() + 0.5 * length;
double midy = blPoint.getY() + 0.5 * height;
double newblPx = midx - length;
double newblPy = midy - height;
length = 2*length;
height = 2*height;
blPoint.setX(newblPx);
blPoint.setY(newblPy);
}
void Rectangle::display() const
{
cout << " Location is (" << blPoint.getX() << ", " << blPoint.getY() << "), length is " << length << ", height is " << height << "; Area is " << area() << "; perimeter is " << perimeter() << ", midpoint is located at (" << midPoint().getX() << ", " << midPoint().getY() << ")" << endl;
}
The only problem's I now have with the program is that it always outputs "Invalid input. Type 'rec' following by the name or 'stop' if done.", and i do not know how to change this. And when you put in a duplicate answer as in rec fire and rec fire, it will say that rec fire is already being used and then continue to prompt for that rectangle instead of asking for another name. ANY HELP would be much appreciated!!
This is wrong
/* Prompt user for first rectangle or 'stop' */
bool read = read_rec(prompt1stName, errorInvalid, errorUsed, inName, list);
// WHILE user input is invalid
while (read == false)
{
// Display "Try again! "
cout << "Try again! " << endl;
bool read = read_rec(prompt1stName, errorInvalid, errorUsed, inName, list);
}
You have two read variables, the read variable in the while condition is referring to the read variable declared first, the read variable declared second is never used. What you want is this
/* Prompt user for first rectangle or 'stop' */
bool read = read_rec(prompt1stName, errorInvalid, errorUsed, inName, list);
// WHILE user input is invalid
while (read == false)
{
// Display "Try again! "
cout << "Try again! " << endl;
read = read_rec(prompt1stName, errorInvalid, errorUsed, inName, list);
}
Now you have only one read variable. This accounts for the second error you describe I think.
Another way of coding this is like this
for (;;)
{
bool read = read_rec(prompt1stName, errorInvalid, errorUsed, inName, list);
if (read)
break;
cout << "Try again! " << endl;
}
In my view this kind of loop is better because it doesn't have the duplicated call to read_rec, so with this style of loop the mistake you made is impossible.