I want to input character and integers by scanf into a structure - c++

Ok, so I'd like to input a one-letter character and three numbers into a structure using scanf, and I want to print all four of them by using a function that prints it. But everytime i run it i get errors saying that i can't run it, or sometimes it prints everything right except the character part, where it would just go as blank.. what could be possibly wrong with this??
#include <stdio.h>
struct Score
{
char a;
float x, y, z;
};
void main(void)
{
void avg(char *a, float x, float y, float z);
char a1 = 'b';
float x1 = 0, y1 = 0, z1 = 0;
printf("enter an alphaber\n");
fflush(stdin);
scanf_s("%c", &a1);
printf("enter three numbers (ex:1,2,3)\n");
fflush(stdin);
scanf_s("%f,%f,%f", &x1, &y1, &z1);
struct Score s1 = { a1, x1, y1, z1 };
avg(s1.a, s1.x, s1.y, s1.z);
}
void avg(char *a, float x, float y, float z)
{
printf("%c (%f,%f,%f) \n", a, x, y, z);
}

The signature of avg() is wrong. The first argument should be not char* but char.
Because I hate MSVC-specific code, your code should be like this.
Note that you should check whether readings are successful.
#include <stdio.h>
struct Score
{
char a;
float x, y, z;
};
int main(void)
{
/* declareing function inside function is unusual, but not bad */
void avg(char a, float x, float y, float z);
char a1 = 'b';
float x1 = 0, y1 = 0, z1 = 0;
printf("enter an alphaber\n");
if (scanf("%c", &a1) != 1) {
puts("read error");
return 1;
}
printf("enter three numbers (ex:1,2,3)\n");
if (scanf("%f,%f,%f", &x1, &y1, &z1) != 3) {
puts("read error");
return 1;
}
struct Score s1 = { a1, x1, y1, z1 };
avg(s1.a, s1.x, s1.y, s1.z);
}
void avg(char a, float x, float y, float z)
{
printf("%c (%f,%f,%f) \n", a, x, y, z);
}

Related

Calculating distance between to points of a triangle using pointers

I'm writing a program, where you input triangle point coordinates, the program checks if the triangle exists and outputs the area of the triangle. I have to use pointers in the program.
class Vertex
{
private:
int x, y;
public:
Vertex(int x, int y) : x(x), y(y) {}
int getX() {
return x;
}
int getY() {
return y;
}
float getDistance(Vertex *anotherVertex)
{
float dist;
int tempx = 0, tempy = 0;
tempx = anotherVertex->getX();
tempy = anotherVertex->getY();
dist = ((tempx - x) * (tempx - x) + (tempy - y) * (tempy - y));
return dist;
}
void setCoord(int x, int y)
{
this->x = x;
this->y = y;
}
};
class Triangle
{
private:
Vertex *a, *b, *c;
public:
Triangle()
{
a = new Vertex(0, 0);
b = new Vertex(0, 0);
c = new Vertex(0, 0);
}
void Set_coord()
{
int x1, y1, x2, y2, x3, y3;
cin >> x1 >> y1 >> x2 >> y2 >> x3 >> y3;
a->setCoord(x1, y1);
b->setCoord(x2, y2);
c->setCoord(x3, y3);
}
bool existTriangle() {
float ab = a->getDistance(b);
float bc = b->getDistance(c);
float ca = c->getDistance(a);
if (ab + bc > ca && ab + ca > bc && bc + ca > ab) {
return true;
}
else {
return false;
}
}
float getArea() {
float p;
float ab = a->getDistance(b);
float bc = b->getDistance(c);
float ca = c->getDistance(a);
p = (ab + bc + ca) / 2;
return sqrt(p * ((p - ab)*(p - bc)*(p - ca)));
}
};
I'm struggling to make the getDistance function working as I'm inexperienced with using pointers, when debugging i'm getting this error in the getX() function.
Exception thrown: read access violation.
this was 0xDDDDDDDD.
EDIT:
here is my main()
int main() {
int n = 0;
cin >> n;
vector<Triangle*> vertices;
for (int i = 0; i < n; i++) {
Triangle* newVertices = new Triangle();
newVertices->Set_coord();
vertices.push_back(newVertices);
delete newVertices;
}
for (int i = 0; i < n; i++)
{
if (vertices[i]->existTriangle())
{
cout << vertices[i]->getArea();
}
}
}
The problem is in your main function ( that's why I asked you to post it:) ):
Triangle* newVertices = new Triangle();
vertices.push_back(newVertices);
delete newVertices;
You dynamically allocate memory, that is pointed to by newVertices.
You store the pointer into the vector.
You delete the memory pointed by newVertices.
As a result, now that pointer is a dangling pointer.
So, you must not delete newVertices into the loop.
Do your thing (computer areas, check it a triangle exists, etc.), and then, when you are done, start deleting your dynamically allocating memory...

no known conversion 'float (MyClass::*)' to 'float (*)'

I am supposed to write a program which has to generate a triangle function, calculate the derivative using forward and backward divided differences and differentiate the triangle function.
So, I wrote some code and have only one problem:
include\MyClass.h|12|note: no known conversion for argument 1 from 'float (MyClass::)(int, float, float)' to 'float ()(int, float, float)'|
My code:
main.cpp
#include <iostream>
#include "MyClass.h"
using namespace std;
int main()
{
MyClass object (3,4,2,0.1);
for (float i=object.x; i<2.5; i+=0.01)
{
cout << object.Triangle(10, 3.14, i) << " ";
}
cout << "////////////////////";
for (float i=object.x; i<2.5; i+=0.01)
{
cout << object.Derivative(&object.Triangle, i, object.con) << " ";
}
}
MyClass.h
#ifndef MYCLASS_H
#define MYCLASS_H
class MyClass
{
public:
MyClass();
MyClass(int k_max, float omega, float x, float con);
~MyClass();
float Triangle (int k_max, float omega, float x);
float Derivative (float (*w) (int k_max, float omega, float x), float var, float con);
float DerivativeCntr (float (*w) (int k_max, float omega, float x), float var, float con);
int k_max;
float omega, x, result, con;
};
#endif // MYCLASS_H
MyClass.cpp
#include "MyClass.h"
MyClass::MyClass() {}
MyClass::~MyClass() {}
MyClass(int K_max, float Omega, float X, float Con)
{
k_max=K_max;
omega=Omega;
x=X;
con=Con;
}
///////////////////////////////////////////////
float Triangle (int k_max, float omega, float x)
{
result=0;
for int (i=0; i<=k_max; i++)
{
result += ( 8*pow(-1, i)*(sin((2*i+1)*omega*x ) / ( pow(2*i+1, 2) * pow(M_PI, 2) )
}
return result;
}
///////////////////////////////////////////////
float Derivative (float (*w) (int k_max, float omega, float x), float var, float con)
{
float result = (w(10, 3.14, var+con) - w(10, 3.14, var))/var;
return result;
}
///////////////////////////////////////////////
float DerivativeCntr (float (*w) (int k_max, float omega, float x), float var, float con)
{
float result=(w(10, 3.14, var)-w(10, 3.14, var-con))/2*var;
return result;
}
I would really appreciate your help, thanks!
EDIT:
I've got this program working, but it's recommended to use a class and required to use a pointer to the function. That's my non object-oriented code:
https://ideone.com/mtPLAo
You have several errors of syntactical nature in your code.
In MyClass.h, change into
float Derivative (float *w, int k_max, float omega, float x, float var, float con);
float DerivativeCntr (float *w, int k_max, float omega, float x, float var, float con);
In MyClass.cpp, all member functions should be prefixed by MyClass:: and also the same for the constructor that takes arguments.

Segmentation fault: 11 - 4D Numerical Integration Error (C++)

I have written three dimensional integration code which calls a gaussian quadrature routine to do the integration as shown below:
#include <iostream>
#include <cmath>
using namespace std;
float qgaus(float (*func)(float), float a, float b)
{
int j;
float xr,xm,dx,s;
static float x[]={0.0,0.1488743389,0.4333953941,
0.6794095682,0.8650633666,0.9739065285};
static float w[]={0.0,0.2955242247,0.2692667193,
0.2190863625,0.1494513491,0.0666713443};
xm = 0.5*(b+a);
xr = 0.5*(b-a);
s = 0;
for (j=1;j<=5;j++)
{
dx=xr*x[j];
s += w[j]*((*func)(xm+dx)+(*func)(xm-dx));
}
return s *= xr;
}
float func(float x,float y,float z)
{
float f = x*y*z;
return f;
}
float yy1(float x)
{
float y = x;
return y;
}
float yy2(float x)
{
float y = 2*x;
return y;
}
float z1(float x,float y)
{
float z = 5*x*y;
return z;
}
float z2(float x,float y)
{
float z = 10*x*x*y;
return z;
}
static float xsav,ysav;
static float (*nrfunc)(float,float,float);
float quad3d(float (*func)(float, float, float), float x1, float x2)
{
float qgaus(float (*func)(float), float a, float b);
float f1(float x);
nrfunc=func;
return qgaus(f1,x1,x2);
}
float f1(float x)
{
float qgaus(float (*func)(float), float a, float b);
float f2(float y);
float yy1(float),yy2(float);
xsav=x;
return qgaus(f2,yy1(x),yy2(x));
}
float f2(float y)
{
float qgaus(float (*func)(float), float a, float b);
float f3(float z);
float z1(float,float),z2(float,float);
ysav = y;
return qgaus(f3,z1(xsav,y),z2(xsav,y));
}
float f3(float z)
{
return (*nrfunc)(xsav,ysav,z);
}
int main ()
{
float R;
R = quad3d(func, 0, 1);
cout << R << endl;
}
This code works perfectly for any three dimensional function I have tested it with. I have attempted to modify it to compute a four dimensional function by replacing the 3d routine with a 4d one:
static float wsav,xsav,ysav;
static float (*nrfunc)(float,float,float,float);
float quad4d(float (*func)(float, float, float, float), float w1, float w2)
{
float qtrap(float (*func)(float), float a, float b);
float f1(float w);
nrfunc=func;
return qtrap(f1,w1,w2);
}
float f1(float w)
{
float qtrap(float (*func)(float), float a, float b);
float f2(float x);
float x1(float),x2(float);
wsav = w;
return qtrap(f2,x1(w),x2(w));
}
float f2(float x)
{
float qtrap(float (*func)(float), float a, float b);
float f3(float y);
float yy1(float,float),yy2(float,float);
xsav = x;
return qtrap(f2,yy1(wsav,x),yy2(wsav,x));
}
float f3(float y)
{
float qtrap(float (*func)(float), float a, float b);
float f4(float z);
float z1(float,float,float),z2(float,float,float);
ysav = y;
return qtrap(f3,z1(wsav,xsav,y),z2(wsav,xsav,y));
}
float f4(float z)
{
float t = (*nrfunc)(wsav,xsav,ysav,z);
return t;
}
This code compiles correctly, but will output "Segmentation fault: 11" when I run it. From what I understand, this implies that there is either some sort of problem with the arrays or a memory allocation error, but neither seem to make sense since there was no problem with the 3d case. Any help with this would be greatly appreciated.

2D numerical integration with infinite limit (C++)

In order to integrate a two dimensional function of the form
$$\int_{1}^\infty \int_{-\sqrt{x^2-1}}^{\sqrt{x^2-1}} e^{-x} \rm{d}y \rm{d}x,$$
I have been attempting to use the following code (written in C++) taken mostly from the Numerical Recipes book which calls a gaussian quadrature routine for the integration:
static float xsav;
static float (*nrfunc)(float,float);
float quad2d(float (*func)(float, float), float x1, float x2)
{
float qgaus(float (*func)(float), float a, float b);
float f1(float x);
nrfunc=func;
return qgaus(f1,x1,x2);
}
float f1(float x)
{
float qgaus(float (*func)(float), float a, float b);
float f2(float y);
float yy1(float),yy2(float);
xsav=x;
return qgaus(f2,yy1(x),yy2(x));
}
float f2(float y)
{
return (*nrfunc)(xsav,y);
}
This code works fine for two dimensional integrals with finite limits, but fails as the outer limit is taken to infinity. To account for this, I have attempted to use a change of variables:
#define FUNC(x) ((*funk)(-log(x))/(x))
float qgaus(float (*funk)(float), float aa, float bb)
{
int j;
float xr,xm,dx,s,a,b;
b=exp(-aa);
a=0.0;
static float x[]={0.0,0.1488743389,0.4333953941,
0.6794095682,0.8650633666,0.9739065285};
static float w[]={0.0,0.2955242247,0.2692667193,
0.2190863625,0.1494513491,0.0666713443};
xm=0.5*(b+a);
xr=0.5*(b-a);
s=0;
for (j=1;j<=5;j++)
{
dx=xr*x[j];
s += w[j]*(FUNC(xm+dx)+FUNC(xm-dx));
}
return s *= xr;
}
float f(float x, float y)
{
float a = exp(-x);
return a;
}
float yy1(float x)
{
float y = -sqrt(x*x-1);
return y;
}
float yy2(float x)
{
float y = sqrt(x*x-1);
return y;
}
static float xsav;
static float (*nrfunc)(float, float);
float quad2d(float (*func)(float, float), float x1, float x2)
{
float qgaus(float (*func)(float), float aa, float bb);
float f1(float x);
nrfunc=func;
float t = qgaus(f1,x1,x2);
return t;
}
float f1(float x)
{
float qgaus(float (*func)(float), float aa, float bb);
float f2(float y);
float yy1(float);
float yy2(float);
xsav=x;
float r = qgaus(f2,yy1(x),yy2(x));
return r;
}
float f2(float y)
{
float k = (*nrfunc)(xsav,y);
return k;
}
int main ()
{
float z;
z = quad2d(f, 1.0, 20.0);
cout << z << endl;
}
but this still doesn't give the right answer. It should be
$2 \times \rm{BesselK}[1,1] \approx 1.20381$
but instead gives
2.15501
Any suggestions on how I could modify this code to account for the infinite limit would be greatly appreciated!

Return Array from Class

I need to return 3 values. X, Y, Z.
I've tried something like this, but it does not work, can anyone help me a bit? I've looked here: Return a float array in C++ and I tried to do same thing, except with 1 dimensional array to return.
class Calculate
{
float myArray[3][4], originalArray[3][4], tempNumbers[4];
float result[3]; // Only works when result is 2 dimensional array, but I need 1 dimension.
public:
Calculate(float x1, float y1, float z1, float r1,
float x2, float y2, float z2, float r2,
float x3, float y3, float z3, float r3)
{
myArray[0][0] = x1;
myArray[0][1] = y1;
myArray[0][2] = z1;
myArray[0][3] = r1;
myArray[1][0] = x2;
myArray[1][1] = y2;
myArray[1][2] = z2;
myArray[1][3] = r2;
myArray[2][0] = x3;
myArray[2][1] = y3;
myArray[2][2] = z3;
myArray[2][3] = r3;
result[0] = 1;
result[1] = 2;
result[2] = 3;
}
float* operator[](int i)
{
return result[i]; //Value type does not match the function type
}
const float* operator[](int i) const
{
return result[i]; //Value type does not match the function type
}
};
Instead of returning a pointer, it's usually better practice to accept a pointer and write out the results there. That way someone can allocate a regular array on the stack and have it initialized by your Calculate.
Something like:
class Calculate
{
float myArray[3][4], originalArray[3][4], tempNumbers[4];
public:
Calculate(float x1, float y1, float z1, float r1,
float x2, float y2, float z2, float r2,
float x3, float y3, float z3, float r3, float *result)
{
myArray[0][0] = x1;
myArray[0][1] = y1;
myArray[0][2] = z1;
myArray[0][3] = r1;
myArray[1][0] = x2;
myArray[1][1] = y2;
myArray[1][2] = z2;
myArray[1][3] = r2;
myArray[2][0] = x3;
myArray[2][1] = y3;
myArray[2][2] = z3;
myArray[2][3] = r3;
result[0] = 1;
result[1] = 2;
result[2] = 3;
}
};
Some other tweaks you can do - separate the constructor from the calculation, since constructors are more for initialization; and pass arrays for safer memory control:
class Calculate
{
float myArray[3][4], originalArray[3][4], tempNumbers[4];
public:
Calculate(const float initArray[3][4])
{
for (int i = 0; i < 3; i++)
for (int j = 0; j < 4; j++)
myArray[i][j] = initArray[i][j];
}
void DoCalculation(float result[3]) const
{
result[0] = 1;
result[1] = 2;
result[2] = 3;
}
};
int main()
{
float myArray[3][4] =
{
{ 0, 1, 2, 3 },
{ 4, 5, 6, 7 },
{ 8, 9, 0, 1 }
};
float result[3];
Calculate calc(myArray);
calc.DoCalculation(result);
return 0;
}
Another alternative is to make the result as a separate structure and either return it as a value or pass it by reference:
struct Result_Type
{
double values[3];
// Alternatively:
// double x;
// double y;
// double z;
};
// Returning a result
const Result_Type calculate_result_1(/* yada yada yada */)
{
Result_type new_result;
new_result.value[0] = 0;
new_result.value[1] = 0;
new_result.value[2] = 0;
return result; // Return the result as a object
}
// Or passing a result to be modified
void clear_result(Result_Type & any_result) // <-- Note pass by reference
{
any_result.value[0] = 0;
any_result.value[1] = 0;
any_result.value[2] = 0;
return;
}
You may find that this is a preferred design since you can pass around results, modify the Result_Type structure to perform operations with other result vectors (math term). The matrix can also be considered as a composition of result vectors.
This may make the code easier to read also.
result[i] is a float, not a float*, so you can do
const float operator[](int i) const
{
return result[i];
}
But I think you do want to return a reference to get the correct semantics, so you want
const float& operator[](int i) const
{
return result[i];
}
float& operator[](int i)
{
return result[i];
}
Right? (I think this is OK -- it compiles but it's been a while since I've done this...)
In the code, where you are getting an error, you are not trying to return a pointer. You are trying to return a single float at the given index.
Calculate c;
float first = c[0];
float second = c[1];
float third = c[2];
If you meant to return a pointer to the results array, then you would have to return the array, e.g
float* GetResult() { return result; }
It probably doesn't matter much which you'll keep because the end effect is pretty much the same. If you overload operator[], you'll have more control, though, as you can check out-of-bound accesses.
Some responses have indicated the use of pointers. The problem is who allocates that pointer and who frees it. Also one needs to check if the incoming pointer is NULL and so on. Instead I would suggest the following declaration of the constructor.
Calculate(float x1, float y1, float z1, float r1,
float x2, float y2, float z2, float r2,
float x3, float y3, float z3, float r3, float (&r)[3])
This is much more safer as references can not be NULL.