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;
}
Related
I am trying to use class to create a program, that with user input, can perform the operations of the Pythagorean theorum, but i get this error:
Error (active) E0304 no instance of overloaded function "getline" matches the argument list
This is my code:
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
class PythagoreanTheorum
{
public:
double a;
double b;
double c;
void seta(double A)
{
a = A;
}
void setb(double B)
{
b = B;
}
void setc(double C)
{
c = C;
}
double calcAreea()
{
return a * pow(a, 2) + b * pow(b, 2) == c * pow(c, 2);
}
};
int main()
{
//Define one right triangles
PythagoreanTheorum righttriangle1;
double a;
double b;
double c;
cout << "Enter the value for a: " << endl;
righttriangle1.a = getline(cin, a);
cout << "Enter the value for b: " << endl;
righttriangle1.b = getline(cin, b);
cout << "Enter the value for c: " << endl;
righttriangle1.c = getline(cin, c);
}
std::getline reads strings, not doubles. So you'd have to read with std::string and then convert it to double (with stod).
You can instead use >> operator for inputs, too:
cout << "Enter the value for a: " << endl;
std::cin >> righttriangle1.a;
cout << "Enter the value for b: " << endl;
std::cin >> righttriangle1.b;
cout << "Enter the value for c: " << endl;
std::cin >> righttriangle1.c;
This is how I would write the code, assuming that calcAreea() in your code is meant to show Pythagoreas Theorem being applied.
My code:
#include <iostream>
#include <cmath>
using namespace std;
class PythagoreanTheorum
{
public:
void seta(double A)
{
a = A;
}
void setb(double B)
{
b = B;
}
void setc(double C)
{
c = C;
}
double calcTheorem()
{
cout<<"Applying Pythagoreas Theorem:"<<pow(a,2)<<"+"<<pow(b,2)<<"="<<pow(c,2);
}
private:
double a;
double b;
double c;
};
int main()
{
//Define one right triangles
//Test -> a = 3, b = 4, c = 5
PythagoreanTheorum righttriangle1;
double a;
double b;
double c;
cout << "Enter the value for a: " << endl;
cin>>a;
righttriangle1.seta(a);
cout << "Enter the value for b: " << endl;
cin>>b;
righttriangle1.setb(b);
cout << "Enter the value for c: " << endl;
cin>>c;
righttriangle1.setc(c);
righttriangle1.calcTheorem();
}
I removed string header file since it wasn't being used, I also used cin instead of getline since that's way better in this case, also I wanted to not use using namespace std; but since it was in your code I retained it & also renamed calcAreea as calcTheorem since it wasn't calculating area
EDIT: I forgot to mention I declared variables in class in private instead of public
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.
Hello I'm currently trying to make a program for an IsingModel and one of the obstacles is to make a class that holds an array. The array that is held by this class is two dimensional and is full of of either -1 or 1's. Since the length of the array is unknown until the class is created I used a class constructor to make this array. The problem is somewhere in that constructor I must be trying to access memory I cannot since I get a segmentation core dump somewhere in that constructor:
#include <time.h> // So we can use time() function
#include <iostream>
#include <string>
#include<stdlib.h>
using namespace std;
class isingModel {
private:
int length;
int relaxationSteps;
double fieldStrength;
double couplingConstant;
public:
//This is the block that throws the segmentation core dump
isingModel() {
int lattice[length][length];
/*Now let's initialize the lattice */
for (int i=1;i<length;i++){
for (int j=1;j<length;j++){
int randNum = rand() % 2; // Generate a random number between 0 and 1
lattice[i][j]=2*(randNum-.5);
cout << lattice[i][j];
}
}
}
void set_values (int,double,double,int);
int area() {return length*fieldStrength*couplingConstant*relaxationSteps;}
};
void isingModel::set_values (int l, double H,double C,int duration) {
length = l;
fieldStrength = H;
couplingConstant = C;
relaxationSteps = duration;
}
int main () {
int L,duration;
double hConstant,couple;
cout << "Enter the length of the lattice: ";
cin >> L;
cout << "Enter the stength of the field: ";
cin >> hConstant;
cout << "Enter the stength of coupling: ";
cin >> couple;
cout << "Enter the number of times to relax the system: ";
cin >> duration;
isingModel iModel;
iModel.set_values (L,hConstant,couple,duration);
cout << "area: " << iModel.area() << endl;
return 0;
}
You're using length before setting it with set_values().
I just want to say that this is my first time trying to learn a programming language so excuse my indifference. I am trying to get used to object oriented programming. The problem is I can't figure out how to get what the user inputted without storing it in a public variable.
#include <iostream>
using namespace std;
class Aclass{
public:
void setx(int a){
x = a;
}
void sety(int b){
y = b;
}
void setsum(int c){
c = sum;
}
int getx(){
return x;
}
int gety(){
return y;
}
int getsum(){
return sum;
}
private:
int x;
int y;
int sum;
int diff;
int mult;
int div;
};
int main()
{
string NB;
cout << "What you like to do ?(Sum, Difference, Multiplication or Division)\n";
cin >> NB;
if(NB == "Sum") {
Aclass Ab;
cout << "Enter Your First Number\n";
Ab.setx(cin >> a);
return 0;
}
}
You need to store the user input in a variable, then pass it to Ab.setx to store the variable in the object, i.e.
int main() {
// Declare your variables
Aclass Ab;
string choice;
int x, y;
// Get user choice
cout << "What you like to do? (Sum, Diff, Mul or Div)" << endl;
cin >> choice;
// Get user inputs
if (choice == "Sum") {
cout << "Enter your first number" << endl;
cin >> x; // Get the user input from 'cin' and store it in 'a'
cout << "Enter your second number" << endl;
cin >> y;
// Pass x, y to the Ab object and store them there
Ab.setx(x);
Ab.sety(y);
cout << "The final sum is: " << Ab.getsum() << endl;
}
return 0;
}
Note: the above code requires an implement of getsum as follows:
class Aclass{
// ...
public:
int getsum(){
return (this->x + this->y);
}
// ...
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!