(C++) multiplication wont give off expected results - c++

hello :) so this is my first time writing a c++ program, im currently using code::blocks tho im pretty sure the issue ive got probably isnt related to the program at all but anyway...
i want to write a simple code, where two "boxes" are created and their volume is calculated and printed on the terminal. ive written this code on a single cpp file:
#include<iostream>
using namespace std;
class Box
{
public:
double length;
double breadth;
double height;
Box(double l, double b, double h)
{
l=length;
b=breadth;
h=height;
}
};
int main()
{
double volume = 0.0;
Box BoxA(2.0, 3.2, 6.0);
Box BoxB(2.5, 4.0, 5.0);
volume = BoxA.length * BoxA.breadth * BoxA.height;
cout << "Box a volume = " << volume <<endl;
volume = BoxB.length * BoxB.breadth * BoxB.height;
cout << "Box b volume = " << volume <<endl;
return 0;
}
so i build and run this thing, no errors but the results i get is this:
box a volume = -0
//and sometimes =0
box b volume = 0
but i dont understand what is wrong here. shouldnt the results be a=38.4 and b=50.0? what am i doing wrong here?

Your constructor assigns values to the passed arguments.
Try this instead:
class Box
{
public:
double length;
double breadth;
double height;
Box(double l, double b, double h)
{
length=l;
breadth=b;
height=h;
}
};
As others have mentioned, there are other improvements that can be made regarding initializer lists and the use of using, and the study of programming in general and c++ in particular is an ongoing journey, never a destination, but this is the direct fix for the immediate problem.

The usual way to write constructors is with initializer lists:
Box(double l, double b, double h) : length(l), breadth(b), height(h)
{
}
This prevent exactly the same error that you had, exchanging the argument and member. If you tried to write : l(length), the compiler would have told you straight away that l is not a member of Box.
You don't even need separate names with initializer lists:
Box(double length, double breadth, double height)
: length(length), breadth(breadth), height(height)
{ }
This does initialize Box::height with the argument height.

#include<iostream>
class Box
{
public:
double length;
double breadth;
double height;
Box(double l, double b, double h)
{
length = l; // assign to the member variables, not parameters
breadth = b;
height = h;
}
};
int main(void)
{
double volume = 0.0;
Box BoxA(2.0, 3.2, 6.0);
Box BoxB(2.5, 4.0, 5.0);
volume = BoxA.length * BoxA.breadth * BoxA.height;
std::cout << "Box a volume = " << volume << std::endl;
volume = BoxB.length * BoxB.breadth * BoxB.height;
std::cout << "Box b volume = " << volume << std::endl;
return 0;
}
This is the refined version of your code. Note that you shouldn't use namespace std. That's a bad programming practice.

Related

C++ Function Polymorphism - Unexpected Behaviour

I'm quite new to C++ and come from a Python background. Basically, I want a collection of "State" objects, each of which should have its own "Distribution" object. Different states can have different types of distribution (uniform, normal, etc.). I want to be able to evaluate the probability of some observation passed to a state without worrying about what that state's distribution is. It occurs to me that's what polymorphism is for. However, if I calculate the PDF for an observation, then change one of the distribution parameters (say, the mean) then I still get the same answer from the PDF function call. Clearly there is some issue of scope, updating, etc. that I'm not understanding; I would be very grateful for an explanation. I've produced a shortened snippet of code which I hope describes my question. While I had a look for similar issues, I couldn't find anything that quite answered my question - nevertheless, sincere apologies if this is a repeat post.
#include <iostream>
#include <math.h>
class Distribution{
/*polymorphic class for probability distributions */
protected:
Distribution( double, double );
public:
double param1, param2;
virtual double pdf( double ) = 0;
};
class NormalDistribution: public Distribution {
/*derived class for a normal distribution */
public:
NormalDistribution( double, double );
double param1, param2;
double pdf( double x ){
return ( 1.0/sqrt( 2.0*pow( param2, 2.0 )*M_PI ) )*exp( -pow( x - param1 , 2.0 )/( 2.0*pow( param2, 2.0 ) ) );
}
};
Distribution::Distribution( double x, double y ){
param1 = x;
param2 = y;
}
NormalDistribution::NormalDistribution( double x, double y ): Distribution( x, y ) {
param1 = x;
param2 = y;
}
class State {
/*simple class for a state object that houses a state's distribution */
public:
Distribution *dist;
State( Distribution * x){
dist = x;
};
};
class myBoringClass{
public:
int x;
int myBoringFunction(int y){
return x*y;
}
};
int main(){
//For polymorphic NormalDistribution class
NormalDistribution nd2(0.0,1.0);
NormalDistribution *np = &nd2;
State myState(np);
//Set an initial mean, std and evaluate the probability density function (PDF) at x=0.5
std::cout << "PDF evaluated at x=0.5, which should be 0.352: " << myState.dist -> pdf(0.5) << std::endl; //this gives the right answer, which is 0.352
//Now change the mean and evaluate the PDF again
myState.dist -> param1 = 2.0;
std::cout << "PDF evaluated at x=0.5, which should be 0.1295: "<< myState.dist -> pdf(0.5) << std::endl; //this gives the wrong answer. Should give 0.1295, but instead gives 0.352.
//For myBoringClass, which works as I would expect
myBoringClass boringClass;
boringClass.x = 4;
std::cout << "Should be 2*4: " << boringClass.myBoringFunction(2) << std::endl; //prints 8
boringClass.x = 5;
std::cout << "Should be 2*5: " << boringClass.myBoringFunction(2) << std::endl; //prints 10
return 0;
}
You have member variables with the same name in the base (Distribution) and derived (NormalDistribution) classes. Remove the double param1, param2; from NormalDistribution.

Best container for coordinates

I'm currently trying to pick up coordinates from a txt file in use of xlib and I've been wondering what's the best container to use for such an endeavor? I was thinking multidimensional arrays since my program is going to work with triangles and a shortest path algorithm I also wanted to ask how best to fill said container using the scan function too, the plan is to use use nested loops in order to fill it up.
EDIT: The txt file that I'm planning on using is a list of triangle coordinates to draw using the xlib function, Then by placing points on the interface, to find the shortest path from a user-defined spot to another, with the triangles serving as obstacles.
int main(int argc,char *argv[])
{
int A,B;
int Trig[A][B];
FILE * pFile;
// First need to scan the file. Need to check if there's a file to look into first.
std::string pFilename = argv[1];
if (pFilename == ""){
cout << "Needs a Filename";
}
pFile = fopen(atoi(pFilename),"r");
// scanf(pFile,"%1s (%d,%d) (%d,%d) (%d,%d)",);
return 0;
}
If those are 2D coordinates, std::pair would be a great choice.
#include <utility>
int main()
{
std::pair<int, int> intCoordinates(5, 3);
std::cout << "x: " << intCoordinates.first;
std::cout << "y: " << intCoordinates.second << "\n";
// -- hocus pocus, array of pairs, use it as normal C array
std::pair<int, int> arr[5];
}
Of course you can change the type of variables.
It can be <double, double> or even <double, int> if you want, that's completely up to you.
More informations: http://www.cplusplus.com/reference/utility/pair/pair/
In this or any other cases, Point struct would do the job:
struct Point {
int x, y;
Point(int a, int b) { this->x = a; this->y = b; }
};
int main()
{
Point p(2,3);
// ...
}
We probably cannot give your more advices unless you bring us more informations about your code.
I faced the same issue recently and found that post. I started using pair as suggested here but at the end it wasn't that easy to use and to maintain so I created my own Struct with some utilities operators.
.hpp
struct Coordinates
{
std::size_t x;
std::size_t y;
Coordinates(std::size_t x, std::size_t y);
void add(std::size_t x, std::size_t y);
Coordinates operator+=(const Coordinates &coordinate);
Coordinates operator+(Coordinates coordinate);
};
.cpp
Coordinates::Coordinates(std::size_t x, std::size_t y) : x(x), y(y)
{
}
void Coordinates::add(std::size_t xAdd, std::size_t yAdd)
{
x += xAdd;
y += yAdd;
}
Coordinates Coordinates::operator+=(const Coordinates &coordinate)
{
add(coordinate.x, coordinate.y);
return *this;
}
Coordinates Coordinates::operator+(Coordinates coordinate)
{
return coordinate += *this;
}
Here is what you can do:
Coordinates myPoint(4, 7);
myPoint += Coordinates(2, 3); // myPoint now contains x = 6 and y = 10
You can also access fields x and y by doing yourPoint.x or yourPoint.y.

Should I be attempting to return an array, or is there a better solution?

A problem set for people learning C++ is
Write a short program to simulate a ball being dropped off of a tower. To start, the user should be asked for the initial height of the tower in meters. Assume normal gravity (9.8 m/s2), and that the ball has no initial velocity. Have the program output the height of the ball above the ground after 0, 1, 2, 3, 4, and 5 seconds. The ball should not go underneath the ground (height 0).
Before starting C++ I had a reasonable, but primarily self taught, knowledge of Java. So looking at the problem it seems like it ought to be split into
input class
output class
calculations class
Physical constants class (recommended by the question setter)
controller ('main') class
The input class would ask the user for a starting height, which would be passed to the controller. The controller would give this and a number of seconds (5) to the calculations class, which would create an array of results and return this to the controller. The controller would hand the array of results to the output class that would print them to the console.
I will put the actual code at the bottom, but it's possibly not needed.
You can probably already see the problem, attempting to return an array. I'm not asking how to get round that problem, there is a workaround here and here. I'm asking, is the problem a result of bad design? Should my program be structured differently, for performance, maintenance or style reasons, such that I would not be attempting to return an array like object?
Here is the code (which works apart from trying to return arrays);
main.cpp
/*
* Just the main class, call other classes and passes variables around
*/
#include <iostream>
#include "dropSim.h"
using namespace std;
int main()
{
double height = getHeight();
int seconds = 5;
double* results = calculateResults(height, seconds);
outputResults(results);
return 0;
}
getHeight.cpp
/*
* Asks the user for a height from which to start the experiment
* SI units
*/
#include <iostream>
using namespace std;
double getHeight()
{
cout << "What height should the experiment start at; ";
double height;
cin >> height;
return height;
}
calculateResults.cpp
/*
* given the initial height and the physical constants, the position of the ball
* is calculated at integer number seconds, beginning at 0
*/
#include "constants.h"
#include <cmath>
#include <iostream>
using namespace std;
double getPosition(double height, double time);
double* calculateResults(double height, int seconds)
{
double positions[seconds + 1];
for(int t = 0; t < seconds + 1; t++)
{
positions[t] = getPosition(height, t);
}
return positions;
}
double getPosition(double height, double time)
{
double position = height - 0.5*constants::gravity*pow(static_cast<double>(time), 2);
if( position < 0) position = 0;
//Commented code is for testing
//cout << position << endl;
return position;
}
outputResults.cpp
/*
* Takes the array of results and prints them in an appropriate format
*/
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
void outputResults(double* results){
string outputText = "";
//The commented code is to test the output method
//Which is working
//double results1[] = {1,2,3,4,5};
//int numResults = sizeof(results1)/sizeof(results1[0]);
int numResults = sizeof(results)/sizeof(results[0]);
//cout << numResults; //= 0 ... Oh
for(int t = 0; t < numResults; t++)
{
ostringstream line;
line << "After " << t << " seconds the height of the object is " << results[t] << "\r";
outputText.append(line.str());
}
cout << outputText;
}
And finally a couple of headers;
dropSim.h
/*
* dropSim.h
*/
#ifndef DROPSIM_H_
#define DROPSIM_H_
double getHeight();
double* calculateResults(double height, int seconds);
void outputResults(double* results);
#endif /* DROPSIM_H_ */
constants.h
/*
* Contains physical constants relevant to simulation.
* SI units
*/
#ifndef CONSTANTS_H_
#define CONSTANTS_H_
namespace constants
{
const double gravity(9.81);
}
#endif /* CONSTANTS_H_ */
I would say that you're over-engineering a big solution to a little problem, but to answer your specific question:
Should my program be structured differently, for performance, maintenance or style reasons, such that I would not be attempting to return an array like object?
Returning an array-like object is fine. But that doesn't mean returning an array, nor does it mean allocating raw memory with new.
And it's not restricted to return values either. When you're starting out with C++, it's probably best to just forget that it has built-in arrays at all. Most of the time, you should be using either std::vector or std::array (or another linear collection such as std::deque).
Built-in arrays should normally be viewed as a special-purpose item, included primarily for compatibility with C, not for everyday use.
It may, however, be worth considering writing your computation in the same style as the algorithms in the standard library. This would mean writing the code to receive an iterator to a destination, and writing its output to wherever that iterator designates.
I'd probably package the height and time together as a set of input parameters, and have a function that generates output based on those:
struct params {
double height;
int seconds;
};
template <class OutIt>
void calc_pos(params const &p, OutIt output) {
for (int i=0; i<p.seconds; i++) {
*output = get_position(p.height, i);
++output;
}
}
This works somewhat more clearly along with the rest of the standard library:
std::vector<double> results;
calc_pos(inputs, std::back_inserter(results));
You can go a few steps further if you like--the standard library has quite a bit to help with a great deal of this. Your calc_pos does little more than invoke another function repeatedly with successive values for the time. You could (for example) use std::iota to generate the successive times, then use std::transform to generate outputs:
std::vector<int> times(6);
std::iota(times.begin(), times.end(), 0);
std::vector<double> distances;
std::transform(times.begin(), times.end(), compute_distance);
This computes the distances as the distance dropped after a given period of time rather than the height above the ground, but given an initial height, computing the difference between the two is quite trivial:
double initial_height = 5;
std::vector<double> heights;
std::transform(distances.begin(), distances.end(),
std::back_inserter(heights),
[=](double v) { return max(initial_height-v, 0); });
At least for now, this doesn't attempt to calculate the ball bouncing when it hits the ground--it just assumes the ball immediately stops when it hits the ground.
You should get rid of self-allocated double * and use std::vector<double> instead. It's not difficult to learn and a basic step in modern C++
This is how I would solve the problem:
#include <cmath>
#include <iostream>
#include <iomanip>
using std::cin;
using std::cout;
using std::endl;
using std::sqrt;
using std::fixed;
using std::setprecision;
using std::max;
using std::setw;
static const double g = 9.81;
class Calculator {
public:
Calculator(double inh) : h(inh)
{
}
void DoWork() const {
double tmax = sqrt(h / ( g / 2));
for (double t=0.0; t<tmax; t+=1.0) {
GenerateOutput(t);
}
GenerateOutput(tmax);
}
private:
void GenerateOutput(double t) const {
double x = g * t * t / 2;
double hremaining = max(h - x, 0.0);
cout << fixed << setprecision(2) << setw(10) << t;
cout << setw(10) << hremaining << endl;
}
double h;
};
int main() {
double h(0.0);
cout << "Enter height in meters: ";
cin >> h;
if (h > 0.0) {
const Calculator calc(h);
calc.DoWork();
} else {
return 1;
}
return 0;
}

I cannot get this code to compile-for an assignment (see comment after code)

I am using MSVS2013. The 'Point' objects are generating errors in the Rectangle.h file. That's as far as I've gotten. (I've marked the lines that are showing errors with: " /** <<---HERE **/ ") I've done several searches for class in class syntax, but I'm either asking the wrong question or not wording it correctly.
Thx,
Mark L. (you guys should prolly add a "newb" tag to that list at the bottom)
// Ch9.DRAFT-Point.h
#ifndef POINT_H
#define POINT_H
class Point
{
public:
Point(double = 0.0, double = 0.0); // constructor
//set functions & get functions
void setX(double);
void setY(double);
double getX();
double getY();
private:
double x; // 0.0 <= x <= 20
double y; // 0.0 <= y <= 20
}; //end class Point
#endif
// end Point.h
///////////////////////////////////////////////////////////////////////
/** THIS FILE IS THE PROBLEM **/
/** the object 'Point' is causing errors **/
// Ch9.DRAFT-Rectangle.h
#ifndef RECTANGLE_H
#define RECTANGLE_H
#include "Point.h"
class Rectangle
{
public:
// default constructor
Rectangle(Point = Point(0.0,1.0), Point(1.0,1.0), /** <<<---HERE**/
Point(1.0,0.0), Point(0.0,0.0)); /** <<<---AND HERE**/
// set x, y, x2, y2 coordinates
void setCoord(Point, Point, Point, Point); /** <<<---AND HERE**/
double length(); // length
double width(); // width
void perimeter(); // perimeter
void area(); // area
bool square(); // square
private:
Point point1; /** <<<---AND HERE**/
Point point2; /** <<<---AND HERE**/
Point point3; /** <<<---AND HERE**/
Point point4; /** <<<---AND HERE**/
}; // end class Rectangle
#endif
// end Rectangle.h
///////////////////////////////////////////////////////////////////////
// Ch9.DRAFT-Point.cpp
// Member function definitions for class Point
#include "Ch9.DRAFT-Point.h"
Point::Point(double xCoord, double yCoord)
{
setX(xCoord); // functio setX()
setY(yCoord); // functio setY()
} // end Point constructor
// set x coordinate
void Point::setX(double xCoord)
{
x = (xCoord >= 0.0 && xCoord <= 20.0) ? xCoord : 0.0;
} // end setX()
// set y coordinate
void Point::setY(double yCoord)
{
y = (yCoord >= 0.0 && yCoord <= 20.0) ? yCoord : 0.0;
} // end setY()
// return x coodinate
double Point::getX()
{
return x;
} //end getX()
// return y coodinate
double Point::getY()
{
return y;
} //end getY()
// end Point.cpp
///////////////////////////////////////////////////////////////////////
// Ch9.DRAFT-Rectangle.cpp
// Member-function definitions for class Rectangle.
#include <iostream>
#include <iomanip>
#include <cmath>
#include "Rectangle.h"
using namespace std;
Rectangle::Rectangle(Point a, Point b, Point c, Point d)
{
setCoord(a, b, c, d); // function setCoord()
} // end Rectangle constructor
void Rectangle::setCoord(Point p1, Point p2, Point p3, Point p4)
{
// verify rectangle formed
if((p1.getY() == p2.getY() && p1.getX() == p4.getX()
p2.getX() == p3.getX() && p3.getY() == p4.getY()))
{
point1 = p1;
point2 = p2;
point3 = p3;
point4 = p4;
} // end if
else
{
cout<< "Coordinates do not form a rectangle!\n"
<< "Use default values.\n";
point1 = Point(0.0,1.0);
point2 = Point(1.0,1.0);
point3 = Point(1.0,0.0);
point4 = Point(0.0,0.0);
} // end else
} // setCoord()
void Rectangle::length( )
{
double side1 = fabs(point4.getY() - point1.getY()); // get side1
double side2 = fabs(point2.getX() - point1.getX()); // get side2
double length = (side1 < side2 ? side1 : side2);
return length;
} // end length()
void Rectangle::width( )
{
double side1 = fabs(point4.getY() - point1.getY()); // get side1
double side2 = fabs(point2.getX() - point1.getX()); // get side2
double width = (side1 < side2 ? side1 : side2);
return width;
} // end width()
void Rectangle::perimeter()
{
cout << fixed << "\nThe perimeter is " << setprecision(1)
<< 2 * (length() + width()) << endl;
} // end perimeter()
void Rectangle::area()
{
cout << fixed << "\nThe area is " << setprecision(1)
<< (length() * width()) << endl;
} // end area()
bool Rectangle::square()
{
return (fabs(point4.getY() - point1.getY()) ==
fabs(point2.getX() - point1.getX());
} // end square()
// end Rectangle.cpp
///////////////////////////////////////////////////////////////////////
// Ch9.DRAFT-Ex09_11.cpp
#include <iostream>
#include "Rectangle.h" // include definition of class Rectangle
using namespace std;
int main()
{
Point w(1.0,1.0);
Point x(5.0,1.0);
Point y(5.0,3.0);
Point z(1.0,3.0);
Point j(0.0,0.0);
Point k(1.0,0.0);
Point m(1.0,1.0);
Point n(0.0,1.0);
Point v(99.0,-2.3);
Rectangle rectangles[4]; // array of 4 rectangles
// output rectangles
for(int i = 0; i < 4; i++)
{
cout << "Rectangle" << i + 1 << ":\n";
switch (i) // init 4 rectangles
{
case 0: // 1st rectangle
rectangles[i] = Rectangle(z, y, x, w);
break;
case 1: // 2nd rectangle
rectangles[i] = Rectangle(j, k, m, n);
break;
case 2: // 3rd rectangle
rectangles[i] = Rectangle(w, x, m, n);
break;
case 3: // 4th rectangle
rectangles[i] = Rectangle(v, x, y, z);
break;
} // end switch
cout << "length = " << rectangles[i].length();
cout << "\nwidth = " << rectangles[i].width();
rectangles[i].perimeter();
rectangles[i].area();
cout << "The rectangle "
<< (rectangles[i].square() ? "is" : "is not")
<< "a square.\n";
} // end for
return 0;
} // end main
// end Ex09_11.cpp
///////////////////////////////////////////////////////////////////////
/**********************************************************************
Chapter 09 exercise instructions:
Do exercise 9.12 on page 429 for 100 points.
This exercise makes a reference to Exercise 9.11. Here is the code for Exercise 9.11: Ex09_11.zip
DO NOT click drag the code into your new project. The code MUST be copied and pasted into new .h/.cpp files which you create. If you drag copy code into your project and then send it to me it probably will not contain that code!! This means you WILL have a rectangle class (Rectangle.h and Rectangle.cpp) and a file called Ex09_11.cpp that has your main function.
Before submitting your project check your archive and be sure it contains your .h and .cpp files.
I will be looking for the following in your program.
*Your program MUST use Cartesian coordinates (x and y coordinates for a total of eight coordinates per figure, each corner of your rectangle is an x,y coordinate). This is a major modification of the supplied code.
*You must follow my previous instructions regarding how to start your program. What you are doing is editing the supplied code so instead of the class Rectangle using width and length it will use cartesian coordinates as defined above.
*Do not have the user enter the coordinates. Hard code them into your program.
*You must include a default constructor for the rectangle class. The default constructor should have the following coordinates ( point 1:(0,0), point 2:(0,1), point 3:(1,1), point 4:(1,0). Be sure the constructor has the set function as described in the textbook assignment. I recommend you pass these points as eight integers (0,0,0,1,1,1,1,0).
*Your program must instantiate four objects of the Rectangle class.
•Your first object should not form a square using your supplied coordinates.
•Your second object should form a square using your coordinates.
•Your third object should should not be instantiated with any points allowing your default constructor points to be used
Hint: Remember that your constructor header can contain default values. If you create an object without passing values those default values will be used. See example program in chapter.
•Your fourth object should not form a rectangle and the default coordinates should replace your original coordinates.
The textbook assignment asks for a set function that tests if any coordinates are over 20. You do not have to write that function.
Do include a function that gets called to check if your coordinates form a square or rectangle as mentioned in the textbook assignment.
Keep your code simple. To decide if the rectangle is a square compare its height verses width.You choose which points and values to compare. If length = width is a square.
This is a programming project intended to show that you know how to program functions and understand constructors..
Review my supplied image of the program's output as a guide.
If you submit the code that I am supplying you will receive zero points.
*AGAIN, do not have the user make the coordinate entries. Code it into the program.
**************************************************************************/
This is not syntacticaly correct...
Rectangle(Point = Point(0.0,1.0), Point(1.0,1.0), /** <<<---HERE**/
Point(1.0,0.0), Point(0.0,0.0)); /** <<<---AND HERE**/
This would be better (and please name your params)
Rectangle(Point first = Point(0.0,1.0), Point second = Point(1.0,1.0), Point third = Point(1.0,0.0), Point fourth = Point(0.0,0.0));
BTW, looking at the comment at the end, it seems to indicate that you did not understand the goal of the project :)
This is a programming project intended to show that you know how to
program functions and understand constructors..
The following code just looks wrong to me.
// default constructor
Rectangle(Point = Point(0.0,1.0), Point(1.0,1.0), /** <<<---HERE**/
Point(1.0,0.0), Point(0.0,0.0)); /** <<<---AND HERE**/
try:
// default constructor
Rectangle(Point a = Point(0.0,1.0), Point b = Point(1.0,1.0),
Point c = Point(1.0,0.0), Point d = Point(0.0,0.0));
This is a programming project intended to show that you know how to program functions and understand constructors..
note you know how to... NOTthe stack overflow community knows how to
ask for help with an error message dont just post all code and ask whats wrong
but try having a look at some C++ tutorials about constructors and initialization

What is wrong with my code? My program will not compile

Ok, so my assignment is to build on an existing code from the book. I have to add the 3rd box and then calculate the total for all 3 boxes. Here is what I've written so far, but it will not compile. Please help me find the problem. Thanks.
The program I'm using is MS Visual C++ and the complile error I get is
error C2447: '{' : missing function header (old-style formal list?)
referring to the { after my int Total_Volume line
// Structures_and_classes.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using std::cout;
using std::endl;
class CBox // Class definition at global scope
{
public:
double m_Length; // Length of a box in inches
double m_Width; // Width of a box in inches
double m_Height; // Height of a box in inches
};
int main();
int Total_Volume;
{
CBox box1;
CBox box2;
CBox box3;
double boxVolume = 0.0; // Stores the volume of a box
box1.m_Height = 18.0; // Define the values
box1.m_Length = 78.0; // of the members of
box1.m_Width = 24.0; // the object box1
box2.m_Height = box1.m_Height - 10; // Define box2 Box 2 H = 8
box2.m_Length = box1.m_Length/2.0; // members in Box 2 L = 39
box2.m_Width = 0.25*box1.m_Length; // terms of box1 Box 2 W = 6
box3.m_Height = box1.m_Height + 2; // Define box3 Box 3 H = 20
box3.m_Length = box1.m_Length - 18; //members in Box 3 L = 50
box3.m_Width = box1.m_Width + 1; //terms of box1 Box 3 W = 25
// Box1
boxVolume = box1.m_Height*box1.m_Length*box1.m_Width;cout << endl;
<< "Volume of box1 = " << boxVolume;
cout << endl;
// Box 2
boxVolume = box2.m_Height*box2.m_Length*box2.m_Width;cout << endl;
<< "Volume of box2 = " << boxVolume;
cout << endl;
// Box 3
boxVolume = box3.m_Height*box3.m_Length*box3.m_Width;cout << endl;
<< "Volume of box3 = " << boxVolume;
cout << endl;
//Calculate Total Volume
Total_Volume = (box1.m_Height*box1.m_Length*box1.m_Width)+
(box2.m_Height*box2.m_Length*box2.m_Width)+
(box3.m_Height*box3.m_Length*box3.m_Width);
return 0;
}
Change:
int main();
int Total_Volume;
{
to:
int main()
{
int Total_Volume;
That will fix your immediate problem, although I suspect you'll have a few more questions today :-)
The actual problem with your current code is that it defines a prototype for main, followed by a file-level variable, followed by a naked brace, which is why it's complaining about a missing function header.
You may also want to consider changing your main function to one of:
int main (int argc, char *argv[])
int main (void)
(probably the second in your case) as these are the two forms required to be supported by the ISO C standard. Implementations are free to accept others if they wish but I usually prefer my code to be as standard as possible. The reason I say "may" is because it's not necessarily required to get your code working, more of a style thing.
int main();
int Total_Volume;
{
should be
int main()
{
int Total_Volume;
It looks like you mixed up a couple lines:
int main();
int Total_Volume;
{
CBox box1;
CBox box2;
CBox box3;
looks like it should be:
int main() {
int Total_Volume;
CBox box1;
CBox box2;
CBox box3;
Try moving
int Total_Volume;
after the {
Goodness me. Please check the preview and at least make sure your question looks like prose plus some code. Edit okay, let's assume that was a glitch that's been sorted out. The rest of my answer still holds.
A little bit of digging suggests the first problem is that you don't have a properly defined main() function. This is the first thing one learns about C++ typically, so in the first instance get that right.
Good luck.
You probably intended to write:
int main()
{
int TotalVolume;
You can't start a block where you did.
You have declared that there will be a function main(), and that there's a global variable TotalVolume, but the anonymous block following these is not allowed.