C++ Overloading Of Functions? Area of Circle - c++

I am trying to get area of circle using my program. But area is not coming in decimals.
#include<iostream>
using namespace std;
float AreaOfCircle(float r);
int AreaOfCircle(int r);
int main()
{int rad;
cout<<"Enter the Radius of Crircle: ";
cin>>rad;
cout<<"The Are of the Cirlcle: "<<AreaOfCircle(rad);
}
float AreaOfCircle(float r)
{
int area=0;
area=2*3.1456*r*r;
return area;
}
int AreaOfCircle(int r)
{
int area=0;
area=2*3.1456*r*r;
return area;
}
But I need answer to some decimal point.

You're not calling the float version of the method.
Either declare your variable as float
float rad;
or cast it to float before you call the method.
AreaOfCircle((float)rad);
You also need to use float instead of int inside the overloaded method:
float AreaOfCircle(float r)
{
float area=0; // <--- float here
area=2*3.1456*r*r;
return area;
}
Also:
area = pi * r * r
length = 2 * pi * r
pi ~= 3.1415

In addition to answer by #Luchian, you need to change the returned value to a float:
float AreaOfCircle(float r)
{
int area=0; // <<----- float area = 0;
area=2*3.1456*r*r;
return area;
}
change to:
float AreaOfCircle(float r)
{
float area=0;
area=2*3.1456*r*r;
return area;
}
or just:
float AreaOfCircle(float r) { return 2*3.1456*r*r; }

The compiler will call the overload it feels is the best match to the types of parameters it is passed. Because you passed an int, it assumed you wanted the int version.
By casting to a float as Luchian suggested (or using a float in the first place) you are telling the compiler that you intend the parameter to be a float type - thus, it picks the float version.

Related

Integrate a function of three variables C++

I spent quiet some time looking on the internet to find a solution to this, maybe it's out there but nothing of what I saw helped me.
I have a function !
double integrand(double r, double phi, double theta)
That I want to integrate with some given definite bounds over the three dimensions. I found multiple lines of code on the internet that implement single variable definite integrals numerical schemes. I was thinking to myself "well, I'll just integrate along one dimension after the other".
Algorithmically speaking what I wanted to do was :
double firstIntegral(double r, double phi) {
double result = integrationFunction(integrand,lower_bound,upper_bound);
return result;
}
And simply do it again two more times. This works easily in languages like Matlab where I can create functions handler anywhere but I don't know how to do it in C++. I would have to first define a function that some r and phi will calculate integrand(r, phi, theta) for any theta and make it in C++ a function of one variable only but I don't know how to do that.
How can I compute the triple integral of my three-variables function in C++ using a one -dimensional integration routine (or anything else really...) ?
This is a very slow and inexact version for integrals over cartesian coordinates, which should work with C++11.
It is using std::function and lambdas to implement the numerical integration. No steps have been taken to optimize this.
A template based solution could be much faster (by several orders of magnitude) than this, because it may allow the compiler to inline and simplify some of the code.
#include<functional>
#include<iostream>
static double integrand(double /*x*/, double y, double /*z*/)
{
return y;
}
double integrate_1d(std::function<double(double)> const &func, double lower, double upper)
{
static const double increment = 0.001;
double integral = 0.0;
for(double x = lower; x < upper; x+=increment) {
integral += func(x) * increment;
}
return integral;
}
double integrate_2d(std::function<double(double, double)> const &func, double lower1, double upper1, double lower2, double upper2)
{
static const double increment = 0.001;
double integral = 0.0;
for(double x = lower2; x < upper2; x+=increment) {
auto func_x = [=](double y){ return func(x, y);};
integral += integrate_1d(func_x, lower1, upper1) * increment;
}
return integral;
}
double integrate_3d(std::function<double(double, double, double)> const &func,
double lower1, double upper1,
double lower2, double upper2,
double lower3, double upper3)
{
static const double increment = 0.001;
double integral = 0.0;
for(double x = lower3; x < upper3; x+=increment) {
auto func_x = [=](double y, double z){ return func(x, y, z);};
integral += integrate_2d(func_x, lower1, upper1, lower2, upper2) * increment;
}
return integral;
}
int main()
{
double integral = integrate_3d(integrand, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0);
std::cout << "Triple integral: " << integral << std::endl;
return 0;
}
You can use functors
#include <iostream>
struct MyFunctorMultiply
{
double m_coeff;
MyFunctorMultiply(double coeff)
{
m_coeff = coeff;
}
double operator()(double value)
{
return m_coeff * value;
}
};
struct MyFunctorAdd
{
double m_a;
MyFunctorAdd(double a)
{
m_a = a;
}
double operator()(double value)
{
return m_a + value;
}
};
template<class t_functor>
double calculate(t_functor functor, double value, double other_param)
{
return functor(value) - other_param;
}
int main()
{
MyFunctorMultiply multiply2(2.);
MyFunctorAdd add3(3.);
double result_a = calculate(multiply2, 4, 1); // should obtain 4 * 2 - 1 = 7
double result_b = calculate(add3, 5, 6); // should obtain 5 + 3 - 6 = 2
std::cout << result_a << std::endl;
std::cout << result_b << std::endl;
}
If your concern is just about getting the right prototype to pass to the integration function, you can very well use alternative data passing mechanisms, the simpler of which is using global variables.
Assuming that the order of integration is on theta, then phi, then r, write three functions of a single argument:
It(theta) computes the integrand from the argument theta passed explicitly and the global phi and r.
Ip(phi) computes the bounds on theta from the argument phi passed explicitly and the global r; it also copies the phi argument to the global variable and invokes integrationFunction(It, lower_t, upper_t).
Ir(r) computes the bounds on phi from the argument r passed explicitly; it also copies the r argument to the global variable and invokes integrationFunction(Ip, lower_p, upper_p).
Now you are ready to call integrationFunction(Ir, lower_r, upper_r).
It may also be that integrationFunction supports a "context" argument where you can store what you want.

Classes arrays of objects value "nan"

I have a problem when I execute the program,the results that I have got is "nan" for the values of vector.I do not exactly where is the mistake. the method distancias generates a correct value but the method variogram does not generate the expected value instead of that generates a value "nan".Sorry for my english.
#include <iostream>
#include <math.h>
//this program is to calculate the kriging puntual
using namespace std;
////
class Points{
private:
float x;
float y;
public:
Points(float a,float b);
Points();
float distancia(float x_1,float y_1);
float variogram(float h);
float valor_1();
float valor_2();
void show(void);
};
Points::Points(){
}
Points::Points(float a,float b){
x=a;
y=b;
}
float Points::distancia(float x_1,float y_1){
float d;
d=pow(pow((x-x_1),2)+pow((y-y_1),2),0.5);
return d;
}
float Points::variogram(float h){
float v,c_0,c_1,a_1;
v=c_0+c_1*(1.5*(h/a_1)-0.5*pow((h/a_1),3));
return v;
}
void Points::show(void){
printf("%.2f,%.2f\n",x,y);
}
float Points::valor_1(){
return x;
}
float Points::valor_2(){
return y;
}
///////
int main(int argc, char** argv) {
float a_1,c_0,c_1; //parameters of variogram
float c,d; // position of point to determinate
float a,b; //positions of all points except the point to determinate
int i=0,n;
int j,k;
Points final; //point to determinate
//this part is to enter the values of function sphere variogram
printf("Enter the paramters of sphere variogram\n");
printf("Enter the value of c_0: ");
scanf("%f",&c_0);
printf("Enter the value of c_1: ");
scanf("%f",&c_1);
printf("Enter the value of a: ");
scanf("%f",&a_1);
//determinating the postion of final point
printf("Enter the position of the point to determinate: ");
scanf("%f,%f",&c,&d);
final=Points(c,d);
final.show();
printf("Enter the name of points for the krigeage: ");
scanf("%i",&n);
Points punto[n];
float vector[n];
do{
printf("Enter the position x,y of the point %i: ",i+1);
scanf("%f,%f",&a,&b);
punto[i]=Points(a,b);
punto[i].show();
vector[i]=punto[i].variogram(punto[i].distancia(c,d));
cout<<vector[i]<<endl;
i=i+1;
}while(i<n);
return 0;
}
The problem is in the following function:
float Points::variogram(float h){
float v,c_0,c_1,a_1;
v=c_0+c_1*(1.5*(h/a_1)-0.5*pow((h/a_1),3));
return v;
}
Here, you are declaring the local variables v, c_0, c_1 and a_1. These values are not initialized, they can contain anything. However, it is not unlikely they actually are equal to zero. So when you calculate h/a_1, the result of that is probably plus or minus infinity. When you subtract two infinities with the same sign from each other, the result will be NaN.
What you should do is pass the values for c_0, c_1 and a_1 from main() to the function:
float Points::variogram(float h, float c_0, float c_1, float a_1){
return c_0+c_1*(1.5*(h/a_1)-0.5*pow((h/a_1),3));
}
...
vector[i]=punto[i].variogram(punto[i].distancia(c,d), c_0, c_1, a_1);
Please compile your code with warnings enabled (if you use GCC, then use the -Wall command line option). Your compiler should then warn you about these uninitialized variables.

Function Overloading Error When Overloading cmath function C++

I'm writing a simple C++ class called Vector2f. I have a class file called Vector2f.cpp and a header file called Vector2f.h.
My Vector2f class has a function called abs which returns a new Vector2f with the absolute value of each of the components of the original Vector2f. I am using the cmath library. However when I try to use cmath's abs function, it thinks I'm referring to some undefined function Vector2f::abs(float) rather than cmath's abs function. Why is there a naming conflict here? Shouldn't C++ be able to resolve that a function called abs that takes a float is only defined in cmath and not in Vector2f.h
Here is my code:
My header file:
//Vector2f.h
#ifndef VECTOR2F_H
#define VECTOR2F_H
class Vector2f
{
private:
float x;
float y;
public:
Vector2f(float x, float y);
float length();
float dot(Vector2f r);
Vector2f normalized();
Vector2f rot(float angle);
Vector2f add(Vector2f r);
Vector2f add(float r);
Vector2f sub(Vector2f r);
Vector2f sub(float r);
Vector2f mul(Vector2f r);
Vector2f mul(float r);
Vector2f div(Vector2f r);
Vector2f div(float r);
Vector2f abs();
float getX();
float getY();
};
#endif // VECTOR2F_H
My class file:
//Vector2f.cpp
#ifndef M_PI
#define M_PI 3.14159265358979323846264338327950288
#endif // M_PI
#include "Vector2f.h"
#include <cmath>
Vector2f::Vector2f(float x, float y)
{
this -> x = x;
this -> y = y;
}
float Vector2f::length()
{
return (float)sqrt(x * x + y * y);
}
float Vector2f::dot(Vector2f r)
{
return x * r.getX() + y * r.getY();
}
Vector2f Vector2f::normalized()
{
float length = Vector2f::length();
float xnormal = x/length;
float ynormal = y/length;
return Vector2f(xnormal, ynormal);
}
Vector2f Vector2f::rot(float angle)
{
double rad = angle * M_PI / 180.0;
double c = cos(rad);
double s = sin(rad);
return Vector2f((float)(x * c - y * s), (float)(x * s + y * c));
}
Vector2f Vector2f::add(Vector2f r)
{
return Vector2f(x + r.getX(), y + r.getY());
}
Vector2f Vector2f::add(float r)
{
return Vector2f(x + r, y + r);
}
Vector2f Vector2f::sub(Vector2f r)
{
return Vector2f(x - r.getX(), y - r.getY());
}
Vector2f Vector2f::sub(float r)
{
return Vector2f(x - r, y - r);
}
Vector2f Vector2f::mul(Vector2f r)
{
return Vector2f(x * r.getX(), y * r.getY());
}
Vector2f Vector2f::mul(float r)
{
return Vector2f(x * r, y * r);
}
Vector2f Vector2f::div(Vector2f r)
{
return Vector2f(x / r.getX(), y / r.getY());
}
Vector2f Vector2f::div(float r)
{
return Vector2f(x / r, y / r);
}
Vector2f Vector2f::abs()
{
//I get the error, "error: no matching function for call to 'Vector2f::abs(float&)'", here
//when trying to call abs(x) and abs(y)
float xabs = abs(x);
float yabs = abs(y);
return Vector2f(xabs, yabs);
}
float Vector2f::getX()
{
return x;
}
float Vector2f::getY()
{
return y;
}
My main file:
//main.cpp
#include <iostream>
#include "Vector2f.h"
using namespace std;
int main()
{
Vector2f a(1.0f,2.0f);
cout<<a.getX()<<','<<a.getY()<<endl;
cout<<a.abs()<<endl;
return 0;
}
Any help would be appreciated.
Edit:
Error message:
error: no matching function for call to 'Vector2f::abs(float&)'
at line 80:
float xabs = abs(x);
error: no matching function for call to 'Vector2f::abs(float&)'
at line 81:
float yabs = abs(y);
The compiler does an unqualified lookup of abs. What happens then depends on what you include and if there is a using declaration (and interestingly on the compiler). Everything in cmath is defined in namespace std, so you have to qualify your call with std::.
Vector2f Vector2f::abs()
{
//I get the error, "undefined reference to `Vector2f::abs(float)'", here
//when trying to call abs(x) and abs(y)
float xabs = std::abs(x);
float yabs = std::abs(y);
return Vector2f(xabs, yabs);
}
If you have a using std::abs or using namespace std somewhere before Vector2d::abs, you can qualify with ::abs only. Compilers are allowed to declare C functions such as abs in the global namespace in addition to namespace std, so depending on the compiler using ::abs may work or not without using declarations at all. Clang 3.8 accepts the code, gcc does not.
PS: I would expect a function Vector2f::abs to compute the vector norm and not a vector with absolute values of the original components. But then I am not a mathematician.

About 200 Errors When Using cmath in Visual Studio 2015

Trying to get code that was compilable in g++ to compile in VS2015. I looked around SO & Google with not much luck, yet cmath is documented in MSDN. I'm guessing I'm missing something really obvious or simple.
cmath is throwing a lot of errors most of the errors I'm getting during compilation, and half are in the form:
the global scope has no "<function>"
others are in the form
'<function>': redefinition; different exception specification
'<function>': identifier not found
'<function>': is not a member of "global namespace"
I don't understand why these errors are being thrown, but, if I use math.h, most of my compilation errors go away (including some in other standard libs that are crapping out, too).
Edit: As requested, the code. I'm using the sqrt & pow functions:
#include "vector.h"
#include <cmath>
using namespace vectormath;
vector::vector()
{
this->_x = 0;
this->_y = 0;
this->_z = 0;
this->_length = 0;
}
vector::vector(float x, float y, float z)
{
this->_x = x;
this->_y = y;
this->_z = z;
this->_length = sqrt(pow(_x, 2) + pow(_y, 2) + pow(_z, 2));
}
vector * vectormath::crossproduct(vector * a, vector * b)
{
vector * result = new vector();
result->_x = a->_y * b->_z - a->_z * b->_y;
result->_y = a->_z * b->_x - a->_x * b->_z;
result->_z = a->_x * b->_y - a->_y * b->_x;
return result;
}
point::point()
{
this->_x = 0.0;
this->_y = 0.0;
this->_z = 0.0;
}
point::point(float x, float y, float z)
{
this->_x = x;
this->_y = y;
this->_z = z;
}
float vectormath::dotproduct(vector a, vector b)
{
return a._x * b._x + a._y * b._y + a._z * b._z;
}
vector * vectormath::add(point * a, vector * b)
{
vector * c = new vector();
c->_x = a->_x + b->_x;
c->_y = a->_y + b->_y;
c->_z = a->_z + b->_z;
return c;
}
Edit: and vector.h
namespace vectormath
{
struct vector
{
float _x;
float _y;
float _z;
float _length;
vector();
vector(float x, float y, float z);
};
struct point
{
float _x;
float _y;
float _z;
point();
point(float x, float y, float z);
};
vector * crossproduct(vector*, vector*);
float dotproduct(vector a, vector b);
vector * add(point * a, vector * b);
}
The difference between
#include <math.h>
and
#include <cmath>
is that the former puts things like sqrt and pow into the global namespace (i.e., you refer to them just by saying sqrt or pow) and the latter puts them into namespace std (i.e., you refer to them by saying std::sqrt or std::pow).
If you want not to have to prefix them with std:: all the time, you can put individual ones in the global namespace explicitly:
using std::sqrt;
or (though this is not recommended) you can pull in the whole of std like this:
using namespace std;
The trouble with that is that there are a lot of names in std and you probably don't really want them all.

Use of Undeclared Identifier "angle"?

I am making a program that converts rectangular coordinates into polar coordinates and whenever I go to run the program it tells me that the "angle" is undeclared even though I am sure I have declared it. As well I know that the program isn't returning anything, I just want to be able to run it for now.
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
#include <cmath>
using namespace std;
double random_float(double min, double max);
void rect_to_polar(double x, double y, double &distance, double &angle);
int main() {
double x, y;
x = random_float(-1, 1);
y = random_float(-1, 1);
rect_to_polar(x, y, distance, angle);
}
double random_float(double min, double max) {
unsigned int n = 2;
srand(n);
return ((double(rand()) / double(RAND_MAX)) * (max - min)) + min;
}
void rect_to_polar(double x, double y, double &distance, double &angle) {
const double toDegrees = 180.0/3.141593;
distance = sqrt(x*x + y*y);
angle = atan(y/x) * toDegrees;
}
You did not declare anything called angle in your main(), but still used the name angle there. Thus the error.
You might want to read up on scopes.
You should declare distance and angle in your main.
int main() {
double x, y, angle, distance;
x = random_float(-1, 1);
y = random_float(-1, 1);
rect_to_polar(x, y, distance, angle);
}