How to use a function c++ - c++

We are starting to learn functions and I've copied the first example we were given below. What is the purpose of float a after int main()? Also could someone give another example of using a function? Thanks
#include <iostream>
using namespace std;
float rectArea (float h, float w)
{
float area;
area = h * w;
return area;
}
int main()
{
float a, h, w;
h = 3.0;
w = 4.0;
cout << "area = " << rectArea(h, w) << endl;
return 0;
}

type specifier float in the first line after main has nothing common with functions because this line defines scalar objects.
Statement
float a, h, w;
defines objects a, h, and w as having type float that is these objects can store float numbers.
I think your professor means the following
int main()
{
float a, h, w;
h = 3.0;
w = 4.0;
a = rectArea(h, w);
cout << "area = " << a << endl;
return 0;
}
Otherwise variable a is defined but not used in the program.
The code would be more clear if he used more meaningful names. For example
int main()
{
float area, height, width;
height = 3.0f;
width = 4.0f;
area = rectArea(height, width);
cout << "area = " << area << endl;
return 0;
}
What is the purpose of float a after int main()?
Shortly speaking the purpose of variable a is to store the result of calculating the area of a rectangle. In fact it is redundant if you are going simply to output the area on console. In this case you could remove the definition of a and write in the output statement
cout << "area = " << rectArea(h, w) << endl;
as it is shown in the original code.

'a' is the variable intended to store the area of the rectangle after multiplying width * height.
'float' describes what type the variable 'a' is, and float is a decimal to 7 digits of precision. So the area of the rectangle is a decimal to 7 digits of precision.

The line:
float a, h, w;
defines 3 variables called a, h and w of type float.
Variable a doesn't have a purpose in this example because it's not used.

Related

calculation of the midpoint of the coordinate values entered by the user. (x, y, z axes) Need class topic

I have an assignment, here is the description:
Create a class named Point. It must have three private float field named as x, y, z to keep coordinates in space and public get and set functions to access these data members ( getX(), getY(), getZ(), setX(), setY(), setZ() ). Create another function that is defined outside of the scope of Point class and named Space. In Space function, you will find the middle point between two points and create a new Point object that will keep calculated coordinates. The written code below must be able to run without errors.
The teacher gave us structure of the code. The code should be like below. only the definition of get, set and space functions can change. I wrote the set and get functions, but I have no idea what to do with the space function. That's why I need help with the space function part.
#include <iostream>
using namespace std;
class Point {
private:
int x, y, z;
public:
float getX();
float getY();
float getZ();
void setX(float x1);
void setY(float y1);
void setZ(float z1);
};
float Point::getX() {
return x;
}
float Point::getY() {
return y;
}
float Point::getZ() {
return z;
}
void Point::setX(float x1) {
x = x1;
}
void Point::setY(float y1) {
y = y1;
}
void Point::setZ(float z1) {
z = z1;
}
Point Space(Point a, Point b)
{
// complete space function
}
int main()
{
float x_, y_, z_;
Point p[3];
for (int i = 0; i < 2; ++i)
{
cout << "Please enter x coordinate for p" << i + 1 << endl;
cin >> x_;
p[i].setX(x_);
cout << "Please enter y coordinate for p" << i + 1 << endl;
cin >> y_;
p[i].setY(y_);
cout << "Please enter z coordinate for p" << i + 1 << endl;
cin >> z_;
p[i].setZ(z_);
}
p[2] = Space(p[0], p[1]);
cout << "Coordinations of middle point (p3) between p1 and p2 is x=" << p[2].getX() << ",y=" << p[2].getY() << ", z=" << p[2].getZ();
return 0;
}
As the instructions says:
In Space function, you will find the middle point between two points and create a new Point object that will keep calculated coordinates.
Per Mid Point Formula in 3D:
A midpoint is the exact center point between two defined points. To find this center point, midpoint formula is applied. In 3-dimensional space, the midpoint between (x1, y1, z1) and (x2, y2, z1) is (x1+x2)/2, (y1+y2)/2, (z1+z2)/2.
So, try this:
Point Space(Point a, Point b)
{
Point mid;
mid.setX((a.getX() + b.getX()) / 2);
mid.setY((a.getY() + b.getY()) / 2);
mid.setZ((a.getZ() + b.getZ()) / 2);
return mid;
}

How do I call operator function to add two objects? [duplicate]

This question already has an answer here:
Overloaded Addition assignment operator in C++ for two /more than two objects?
(1 answer)
Closed 5 years ago.
Trying to develop operator == to compare two balls where two balls are considered equal if they have the same radius and operator > to compare two balls. To see if one ball has a bigger radius than another one, for let's say ball x is > than another ball y. += to add the volume of the right-side-operand to the volume of the left-side-operand. It is like to melt two metal balls to make one metal ball. The new ball's radius is cube root of (r1^3 + r2^3). Wish to use pow() function to calculate the cube value and cube root value. operator + to add the two balls together and return a new ball. The size of the new ball is the sum of the size of the two operands connected by the +.
In the main() function, couldn't add ball m(10) with ball n(20) to create another ball d, like d = m+n.
int main()
{
//use ball
ball x; float re;
//radius of ball y is set to 10
ball y(10);
//asks for radius of x?
cout << "Enter radius for ball x: ";
cin >> re;
//sets the radius of x
x.set_radius(re);
ball m(10);
ball n(20);
ball d;
d = m + n;
//cout << "The radius of ball d is " << m.;
system("pause");
return 0;
}
//ball.h
{
class ball
{
public:
//sets the intial raduis to 0
ball() {
radius = 0;
}
ball(float radii) {
radius = radii;
}
float get_radius() {
return radius;
}
void set_radius(float redly) {
radius = redly;
}
bool operator == (ball x) {
if (radius == x.radius)
return true;
else
return false;
}
bool operator > (ball x) {
if (radius > x.radius)
return true;
else
return false;
}
bool operator += (ball x) {
radius += x.radius;
}
ball operator + (ball a, ball b) {
ball d;
d += a;
d += b;
return d;
}
private:
float radius;
};
}
#endif
If you are only looking for (x_volume/ y_volume)% and (x_surfacearea/y_surfacearea)%
I suggest doing :
float vol_over_y() {
float v;
v = ((radius * radius * radius)/(10*10*10));
return v;
}
float sa_over_y() {
float a;
a = (radius * radius /(10*10));
return a;
}
because other constants like (4.0/3.0)* 3.14 in volume and 3.14 in surface area cancel out.
If in case y changes,
float vol_over_y(float y_rad) {
float v;
v = ((radius * radius * radius)/(y_rad*y_rad*y_rad));
return v;
}
float sa_over_y(float y_rad) {
float a;
a = (radius * radius /(y_rad*y_rad));
return a;
}
You thought too much. It is simply a little tweak in your main logic:
ball x;
ball y(10);
// your code to construct x
cout << "The volume of x is " << ( x.volume() / y.volume() )<< "% of the volume of y."<< endl;
// similar for surface area, try it out yourself
If in case you really need to do it in a method(which is quite ridiculous imho), you should just pass the other ball in and calculate:
float volume_ratio_to(const ball& base) {
return volume() / base.volume();
}
And your main logic become
cout << "The volume of x is " << x.volume_ratio_to(y) << "% of the volume of y."<< endl;
Edited for your updated question:
The reason why + operator does not work for you is because you didn't overloaded the operator right.
If you want it to be member of ball, the + operator should only takes one argument.
i.e. looks like:
class ball {
//....
ball operator + (ball another);
}
Or, don't make it member of ball:
// outside ball class
ball operator + (ball a, ball b) {....}
Refer to Overloaded Addition assignment operator in C++ for two /more than two objects? for more detailed description on how to overload addition operator.
There are quite a lot of other problems in your code too
You should have passed balls to methods by reference instead of by value
You should have considered adding const in various places
You += logic is totally wrong. Pay attention to what you quoted:
+= to add the volume of the right-side-operand to the volume of the
left-side-operand. It is like to melt two metal balls to make one
metal ball. The new ball's radius is cube root of (r1^3 + r2^3)
//This helps
int main()
{
//use ball
ball x; float re;
ball y(10);
cout << "Enter radius for ball x: " << endl;
cin >> re;
x.setl(re);
cout << "The volume of x is " << (x.volume()/y.volume())*100 << "%
of the volume of y."<< endl;
cout << "The surfacearea of x box is " <<
(x.surface_area()/y.surface_area())*100 << "% of
the surfacearea of y." << endl;
system("pause");
return 0;
}
//ball.h
#pragma once
#ifndef Ball
#define Ball
namespace bsize
{
class ball
{
public:
ball(){
radius = 0;
}
ball(float radii) {
radius = radii;
}
float volume() {
float v;
v = ((4.0/3.0)* 3.14 * (radius * radius * radius));
return v;
}
float surface_area() {
float a;
a = (4 * 3.14 * radius * radius);
return a;
}
float get_radius(){
return radius;
}
void set_radius(float redly) {
radius = redly;
}
private:
float radius;
};
}
#endif

C++ how to find area of square or rectangle with vector of coordinates

How do I find the area of square or rectangle assuming user has entered some accurate points to form a square or rectangle.
I need to calculate the area inside the square class and rectangle class respectively.
I have 2 vector of coordinates, coordX and coordY.
My idea is when either or x or y has same value it will be a line and I can find the distance x2 but I'm not sure how to implement it in code.
double Square::computeArea() {
double area;
for (int x = 0; x < coordX.size; x++) {
for (int y = 0; y < coordY.size; y++) {
if (coordX[x] == coordY[y])
{
//....
}
}
}
return area;
}
This is how i populate my vector with user input
Square Square;
for ( int i = 1; i <= 4; i++) {
cout << "Please enter x-coordinate of pt " << i << ": ";
cin >> x;
Square.setXCoordinate(x);
cout << "Please enter y-coordinate of pt " << i << ": ";
cin >> y;
Square.setYCoordinate(y);
}
this is my mutator function in my class. Square inherit from ShapeTwoD
void ShapeTwoD::setXCoordinate(int x) {
coordX.push_back(x);
}
void ShapeTwoD::setYCoordinate(int y) {
coordY.push_back(y);
}
No need for square root.
Take two edges from one vertex, rotate one by 90°, take dot product.
double dx1 = coordX[3] - coordX[0];
double dy1 = coordY[3] - coordY[0];
double dx2 = coordX[1] - coordX[0];
double dy2 = coordY[1] - coordY[0];
double area = abs(dx1*dy2 - dy1*dx2)
As a bonus, this will calculate the correct area for all parallelograms, not just rectangles.
This assumes, the points are entered in clockwise or couter-clockwise order. If that's not the case, find out which point has the greatest distance to point[0] then discard it and use the other two instead of 1 and 3 above.
Assuming your coordinates are something like
// 3-----------2
// | |
// | |
// 0-----------1
Then you could do
#include <cmath>
double distance(double x1, double x2, double y1, double y2)
{
return std::sqrt(std::pow(x2 - x1, 2) + std::pow(y2 - y1, 2));
}
double Square::computeArea() const
{
double length = distance(coordX[0], coordX[1], coordY[0], coordY[1]);
double width = distance(coordX[0], coordX[3], coordY[0], coordY[3]);
return length * width;
}
This allows your rectangle to be at any arbitrary orientation, instead of x-y axis aligned. You just need to maintain a convention of the indexes of the corners, like in my example diagram.

Jumping into C++ Chapter 13 Practice Prob No4 - Pointers

I've having trouble understanding the wording of this question and what it means by returning the second value through a pointer parameter?
The problem is:
Write a function that takes input arguments and provides two seperate results to the caller, one that is the result of multiplying the two argumentsm the other the result of adding them. Since you can directly return only one value from a funciton you'll need the seecond value to be returned through a pointer or references paramter.
This is what I've done so far.
int do_math(int *x, int *y)
{
int i =*x + *y;
int u = *x * *y;
int *p_u = &u;
return i;
}
void caller()
{
int x = 10;
int y = 5;
std::cout << do_math(&x, &y);
//std::cout << *u;
}
I think all they're wanting you to do is to demonstrate your understanding of the difference between passing arguments by value and passing them by reference.
Here is a sample code that shows that although my function is only returning one value "i = X+Y", It is also changing the value of Y to (Y * X).
Of course if you do need Y's value to stay unchanged, you could use a third variable that is equal to Y's value and pass its reference as an extra argument to your function.
You could run the code bellow to see what's happening to X and Y before and after calling the function.
Hope this helps.
#include <iostream>
using namespace std;
int do_math(int value1, int *pointer_to_value2)
{
int i = value1 * *pointer_to_value2;
*pointer_to_value2 = *pointer_to_value2 + value1; // y changes here
return i;
}
int main( int argc, char ** argv ) {
int x = 10;
int y = 5;
cout << "X before function call " << x << endl;
cout << "Y before function call " << y << endl;
int product = do_math(x, &y);
cout << "X after function call " << x << endl;
cout << "Y after function call " << y << endl;
cout << "What the function returns " << product << endl;
return 0;
}
In the assignment there is written
Write a function that takes input arguments ...
So there is no any need to declare these input parameters as pointers.
The function could look like
int do_math( int x, int y, int &sum )
{
sum = x + y;
return x * y;
}
or
int do_math( int x, int y, int *sum )
{
*sum = x + y;
return x * y;
}
In these function definitions the sum and the product can be exchanged as the parameter and return value
As for me the I would write the function either as
void do_math( int x, int y, long long &sum, long long &product )
{
sum = x + y;
product = x * y;
}
or
#include <utility>
//...
std::pair<long long, long long> do_math( int x, int y )
{
return std::pair<long long, long long>( x + y, x * y );
}
void caller()
{
int x = 10;
int y = 5;
std::pair<long long, long long> result = do_math( x, y );
std::cout << "Sum is equal to " << result.first
<< " and product is equal to " << result.second
<< std::endl;
}
Edit: I would like to explain why this statement
std::cout << "sum is " << do_math(x, y, result) << " and result is " << result;
is wrong.
The order of evaluation of subexpressions and function argument is unspecified. So in the statement above some compilers can output value of result before evaluation function call do_math(x, y, result)
So the behaviour of the program will be unpredictable because you can get different results depending on using the compiler.
Edit: As for your code from a comment then it should look like
#include <iostream>
int do_math( int x, int y, int *p_u )
{
int i = x + y;
*p_u = x * y;
return i;
}
int main()
{
int x = 10;
int y = 5;
int u;
int i = do_math( x, y, &u );
std::cout << i << std::endl;
std::cout << u << std::endl;
}
Also take into account that in general case it is better to define variables i and u as having type long long because for example the product of two big integers can not fit in an object of type int.
The wording is kind of contrived but I believe the task asks you to
return the multiplication as the return value of the function, and
since you can't return two types at once (except if you wrap them up somehow), you should use a third parameter as a storage area for the sum:
#include <iostream>
/* Multiplication in here */ int do_math(int x, int y, int& result/* Addition in here */)
{
result = x + y;
return x*y;
}
int main() {
int x = 10;
int y = 5;
int addition = 0;
int multiplication = do_math(x, y, addition);
std::cout << "multiplication is " << multiplication << " and sum is " << addition;
}
Example
It's not specifically asking you to use two parameters for the function.
A typical solution to the intent of the exercise text…
” Write a function that takes input arguments and provides two seperate results to the caller, one that is the result of multiplying the two argumentsm the other the result of adding them. Since you can directly return only one value from a funciton you'll need the seecond value to be returned through a pointer or references paramter
… is
auto product_and_sum( double& sum, double const a, double const b )
-> double
{
sum = a + b;
return a*b;
}
#include <iostream>
using namespace std;
auto main() -> int
{
double product;
double sum;
product = product_and_sum( sum, 2, 3 );
cout << product << ", " << sum << endl;
}
This code is unnatural in that one result is returned while the other is an out-argument.
It's done that way because the exercise text indicates that one should do it that way.
A more natural way to do the same is to return both, as e.g. a std::pair:
#include <utility> // std::pair, std::make_pair
using namespace std;
auto product_and_sum( double const a, double const b )
-> pair<double, double>
{
return make_pair( a*b, a+b );
}
#include <iostream>
#include <tuple> // std::tie
auto main() -> int
{
double product;
double sum;
tie( product, sum ) = product_and_sum( 2, 3 );
cout << product << ", " << sum << endl;
}
As the second program illustrates, the last sentence of the exercise text,
” Since you can directly return only one value from a funciton you'll need the seecond value to be returned through a pointer or references paramter
… is just not true. I suspect the author had meant the word “directly” to clarify that this excluded the case of a non-basic type. But even so the conclusion is incorrect.
What you need to do is provide another parameter to the function - the pointer or the reference to the variable where you want to store your other result:
int do_math(int *x, int *y, int &res) //or int *res
{
...
res = *x * *y;
...
}
Then make a result variable in main and pass it to the function

Why does the area come back as 0?

Here's the code.
int a;
int pi = 3.14;
int area;
int main()
{
cout << "Input the radius of the circle ";
cin >> a;
a *= a *= pi >> area;
cout << "The area is " << area;
}
The >> operator when used with numbers is right shift, not assignment. You want something like
area = a * a * pi;
Update
You also need to use a floating point type or your answer won't be what you expect.
float a;
float pi = 3.14f;
float area;
I don't have enough patience to decipher your strange code. How about just area = a * a * pi?
Your code doesn't make any sense.
pi(and all your other variables) need to be double or float,... not int. An int can only contain an integral number. And pi is obviously not integral.
a *= a *= pi >> area; should be area = a * a * pi;
>> is a bitshift, not an assignment to the right side
*= is multiply assign and not just multiply. i.e. it is similar to left=left*right
The area of a circle is pi * r * r therefore you would want to do;
a = a * a * pi
Hope that helps
and they all would need to be floats.
Your code doesn't do what I think you wanted it to do. You don't assign to variables with >>; that is only for stream extraction (and bitshifting).
Also, a *= a *= pi probably doesn't do what you think it does.
Also, you want floating-point values, not int. An "int" pi is just 3.
Also, you should have error checking on your stream extraction!
Try:
int main()
{
const float pi = 3.14;
float a;
cout << "Input the radius of the circle ";
if (!(cin >> a)) {
cout << "Invalid radius!";
return 1;
}
float area = (a * a * pi);
cout << "The area is " << area;
}
int pi = 3.14;
Wrong datatype. Assigning double value to int? That's wrong.
Write this:
double pi = 3.14;
And likewise, change other datatypes to double as well.
Because you're using int, or integer, for all your variables. You want to use doubles or even floats. (doubles are more precise).
All your variables are declared as int, which simply drops any fractional portion assigned to it. To work with floating-point values, use double instead.
Also, your equation in almost incomprehensible. Not sure what you're trying to do there.