I had a lot of problems with this project, I figured out a lot. but this one I can't
Here I have some calculations, and then I need this "y" variable to pass to next .cpp
#include <iostream>
#include <math.h>
using namespace std;
int Ing(int number, float y)
{
y = 0;
float Lngth = 0;
for(; number != 0; number /= 10, Lngth++);
float n = nearbyint(sqrt(Lngth));
y = Lngth * pow(10, n);
return (y);
}
here is the next .cpp
#include <iostream>
#include "InitialGuess.h"
#include <math.h>
using namespace std;
int SquareRoot(int number, int th)
{
float iGuess = Ing(y);
float x = iGuess;
for (int k=1; k< th; ++k)
{
x = (x + (number / x ))/2;
}
cout<<x;
return (x);
}
But on compilation It gives me error that "y" was not declared in this scope.
Where I've made a mistake?
Thank you
On this line
float iGuess = Ing(y);
you don't have y declared, which causes the error. What value do you want to pass to Ing()?
You've got 2 parameters defined for Ing(int, float) but only calling it with one.
y = 0;
should be
int y = 0;
because y has not yet be declared at this point and you are defining a variable.
Related
I am writing some code that prints out a sum series using a loop and a function.
I intend the equation to look like this
m(i) = (1/2) + (2/3) + ... (i / i + 1)
The problem is that my code always gives me incorrect answers and not printing what it's supposed to. For example, when I input 1 into 1 the answer should be 0.5
This is my code:
#include <iostream>
using namespace std;
void sumSeries(int x);
int main() {
sumSeries(1);
return 0;
}
void sumSeries(int x){
double sum = 0;
for(int i = 0; i < x; i++){
sum = (x/x + 1);
sum += sum;
}
cout<<sum;
}
Indeed, you overwrite your sum but also take care of your integer division.
You may change it as sum += i/(double)(i + 1);
#include <iostream>
using namespace std;
void sumSeries(int x);
int main() {
sumSeries(5);
return 0;
}
void sumSeries(int x){
if (x<0)
{
return;
}
double sum = 0;
for(int i = 0; i < x; i++){
sum += i/(double)(i + 1);
}
cout<<sum;
}
I see two problems in your code.
First: (x/x+1) != (x/(x+1)), in this case C++ obeys the normal point before line calculation rules.
Second: You are overwriting your sum in each iteration, instead of that you should direct add to sum: sum+=x/(x+1)
And a third issue, as noted by Simon Kraemer, is that you are using integer division, to get the correct results you must cast at least one of the operands to a floating point number.
What you want is:
void sumSeries(int x){
double sum = 0;
for(int i = 1; i <= x; i++){ // include i in the list
sum += static_cast<double>(i)/(i + 1); // force the operation as double
}
cout<<sum;
}
your mathematical expression has something not normal. Do you mean M(i)= sum(1-i){i/i+1}? , or 1/2 and 1/3 are constants?
in your case as gerum answered it is a small Operator Precedence problem to learn how the C++ compiler prioritize the operators follow here.
your function also should have a guard against zero denominator (undefined values).
Also you should observe that you take int/int division which will ignore the remaining value. then you should consider that by converting the numerator or the denominator to double before the division here .
then your code should be:
#include <iostream>
using namespace std;
void sumSeries(int x);
int main() {
sumSeries(1);
return 0;
}
void sumSeries(int x){
double sum = 0;
for(int i = 0; i < x; i++){
if ((x+1)!=0){
sum += (double)x/(x + 1);
}
// the else will apply only if x==-1
else {
cout<<"the denominator is zero"<<endl;
throw;
}
}
cout<<sum;
}
I am new to C++ and trying to make a program to calculate bond price, the original code works well but I have difficulties transferring it to OOP. mode. The program uses two arrays and a integer to do calculation. I used a loop in constructor to initialize data members (learned from stack over flow). it looks fine but I experienced one error like: no matching function for call to member function. the data can't be passed to member function. I was trapped here a whole day. Could anybody give me some insights? Thank you. The code follows:
#include <array>
#ifndef DRAFT_H
#define DRAFT_H
class Draft
{
public:
Draft(int, double [], double[]);
double F (double);
void Bcalculator (int, double[], double[]);
void printResult();
void printDfactor();
private:
double discF[3]{};
double bPrice {0};
double bDuration {0};
double bConvexity {0};
double term[3];
double cFlow[3];
int sizeofArray;
private:
};
#endif // DRAFT_H
#include "Draft.h"
#include <iostream>
#include <cmath>
#include <array>
#include <iomanip>
using namespace std;
Draft::Draft( int arraySize, double termArr[], double cFlowArr[]):sizeofArray{arraySize}{
for (int i = 0; i < 3; i++){
term[i] = termArr[i];
cFlow[i] = cFlowArr[i];}
}
double Draft::F (double x){
return 0.05 / (1 + exp(-pow((1 + x),2)));
}
void Draft::Bcalculator(int sizeofArray, double term[], double cFlow[]){
double a = 0;
int n = 16;
for (int k =0; k < sizeofArray; k++){
double h = (term[k] - a)/n;
double x[n], fx[n];
for (int i = 0; i <= n; i++){
x[i] = a + i * h;
fx[i] = F(x[i]);
}
double result = 0;
double discF[]{};
for (int i = 0; i <= n; i ++){
if (i == 0 || i == n){
result += fx[i];
}
else if (i % 2 != 0){
result += 4 * fx[i];
}
else {
result += 2 * fx[i];
}
}
result = result * (h/3);
discF[k] = exp (- result);
bPrice += discF[k] * cFlow[k];
bDuration += term[k] * cFlow[k] * discF[k];
bConvexity += pow(term[k], 2) * cFlow[k] * discF[k];
}
bDuration = bDuration / bPrice;
bConvexity = bConvexity / bPrice;
}
void Draft::printDfactor(){
for (int k = 0; k < sizeofArray; k++) {
cout << k + 1 << setw (20) << discF[k] << endl;
}
}
void Draft::printResult()
{
cout << "Bond Price = " << setw(20) << bPrice << endl;
cout << "Bond duration = " <<setw(20) << bDuration <<endl;
cout << "Bond Convexity = " << setw(20) << bConvexity << "\n";
}
#include "Draft.h"
#include <iostream>
#include <cmath>
#include <array>
#include <iomanip>
using namespace std;
int main (){
double termArray[3]{1, 2, 3};
double cFlowArray[3]{5, 5, 105};
int arraySize = 3;
Draft bond1 (arraySize, termArray, cFlowArray);
Draft::Bcalculator();
bond1.printResult();
bond1.printDfactor();
return 0;
}
The error is:
main.cpp|20|error: no matching function for call to
'Draft::Bcalculator include\Draft.h|18|note: candidate: 'void
Draft::Bcalculator(int, double*, double*)'| include\Draft.h|18|note:
candidate expects 3 arguments, 0 provided|
There are two problems in your code.
Definition does not match call. You defined Bcalculator as:
void Draft::Bcalculator(int sizeofArray, double term[], double cFlow[])
But then you call it without arguments:
Draft::Bcalculator();
To be able to call Draft::Bcalculator() you need to add static in the definition:
static void Draft::Bcalculator(int sizeofArray, double term[], double cFlow[])
If you do not want to make it static, call it the normal way, i.e. Draft d{...}; d.Bcalculator().
EDITED
I realized that Bcalculator is using the same three parameters you use to construct and store in Draft class. Therefore, you should call Bcalculator without any arguments and use the class members termArray, cFlowArray and arraySize:
int main ()
{
double termArray[3]{1, 2, 3};
double cFlowArray[3]{5, 5, 105};
int arraySize = 3;
Draft bond1 (arraySize, termArray, cFlowArray);
bond1.Bcalculator();
bond1.printResult();
bond1.printDfactor();
return 0;
}
Then, your definition and implementation of this function has to be changed accordingly:
class Draft
{
public:
...
void Bcalculator(); // <- remove parameters in this definition
private:
double term[3];
double cFlow[3];
int sizeofArray;
}
void Draft::Bcalculator() // <- remove parameters in this implementation
{
... // use automatically the private members term, cFlow and sizeofArray
}
This code works, I compiled it.
Regards!
I have defined a variable in my code:
double R0;
When I set the variable less than 0.9, the code doesn’t run without no error! I have also written cout<<2; exactly after main(){ but the program doesn’t even show that! I am very confused :( what is the problem? When I change R0 to 0.9 or bigger than it, the code runs. This is the most minimal example I could provide:
#include <iostream>
#include <math.h>
#include <vector>
#include <functional>
#include <string>
#include <sstream>
using namespace std;
vector<double> getBoxCoords(int boxID, double L, double R0, int nbox)
{
vector<double> coords(4);
int yID = ceil((double)(boxID+1)/nbox);
int xID = fmod((boxID+1-(yID-1)*nbox), nbox);
if(xID==0)
xID = nbox;
coords[0] = (xID-1) * R0; // minX
coords[1] = (yID-1) * R0; // minY
coords[2] = min(xID * R0, L); // maxX
coords[3] = min(yID * R0, L); // maxY
return coords;
}
double PBC(double pos, double L)
{
if(fabs(pos) > L / 2.0)
return L-fabs(pos);
else
return fabs(pos);
}
int main()
{
std::cout << 2;
int N=100;
double rho=4.0, v0=0.03, eta=0.2, R0=0.03;
double L = pow(N/rho,0.5);
int nbox = (int)ceil(L/R0);
vector<vector<int>> box_neighbors;
vector<int> indices;
for(int i = 0; i < nbox * nbox; i++) //NUMBER OF BOX
{
vector<double> ci = getBoxCoords(i, L, R0, nbox);
indices.clear();
for(int j = 0; j < nbox * nbox; j++)
{
vector<double> cj = getBoxCoords(j, L, R0, nbox);
bool xflag=false,
yflag=false;
if (PBC(ci[0]-cj[0],L)<R0 || PBC(ci[0]-cj[2],L)<R0 || PBC(ci[2]-cj[0],L)<R0 || PBC(ci[2]-cj[2],L)<R0)
xflag=true;
if (PBC(ci[1]-cj[1],L)<R0 || PBC(ci[1]-cj[3],L)<R0 || PBC(ci[3]-cj[1],L)<R0 || PBC(ci[3]-cj[3],L)<R0)
yflag=true;
if(xflag && yflag)
indices.push_back(j);
}
box_neighbors.push_back(indices);
}
return 0;
}
How can I remove the problem? Could anyone provide a runnable answer?
First thing first, the debug std::cout << 2; is now shown because you do not end the stream, proper way of doing it is
std::cout << 2 << std::endl;
then you will be able to see the debugging message.
Secondly, Your program runs, but takes too much time to finish, when R0 is small. For the given value, that is, 0.03, both layers of the loop will execute nbox * nbox times which is 27889, thus, 777796321 in total.
#include<iostream>
#include<cmath>
using namespace std;
int e=0.001;
double yk(int k,double x){
if(k==0) return 1;
return 0.5*(yk(k-1,x) + x/yk(k-1,x));
}
double square(double x,int k)
{
if(fabs(yk(k,x)*yk(k,x) - x)<e) return yk;
return square(x,k+1);
}
int main()
{
cout<<yk(5,2);
return 0;
}
I need to calculate the square root of a number with Newton's formula which calculates y[k] till fabs(y[k] * y[k] -x)>e (a small number like 0.0001);
So if sqrt (2)= 1.41421356237 and e=0.0001 my function must back 1.4142 .
..This is the program I wrote.. I know that it is buggy, so i will be very thankful if sb help me :)))
The variable e should be float or double.
The error you get is not because of the fabs function, it is because you are trying to return a pointer to the yk function, but square returns a double
#include <iostream>
#include <cmath>
using namespace std;
double e=0.001;
double yk(int k,double x){
if(k==0) return 1;
return 0.5*(yk(k-1,x) + x/yk(k-1,x));
}
double square(double x,int k)
{
double res = yk(k, x);
if (fabs(res*res - x) < e) return res;
return square(x,k+1);
}
int main()
{
cout << yk(5,2); // Actually you don't call square....
// it works even if you do square(2, 5), this way you get the root of two
// doing at least 5 iterations, and if it is not enough (error > e) the
// computer goes on until it gets an error < e
return 0;
}
I'm getting an error saying that "adjacencymatrix' was not used in this scope" right at the end of main (before the function makebond at the end) (the commented line 112 "BROKEN LINE"). Why? Sorry about this being simple. I'm compiling with g++ ($ g++ a.c -o f).
Heres the code:
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
using namespace std;
#define PI 3.1415926535897932384626433832795
#define sqr(x) ((x)*(x))
#define count 500
double density;
double volume;
int N;
double beta = 0.1;
double R = 5;
double rob = 1;
int dimension = 2;
double eps=0.1; // Increase in density
double mindensity = 0; // Minimum density
double maxdensity = 8; // max.dens (scaled for the sake of ensuring int()
int makebond(double x);
int main(){
srand(time(0));
for (int rho=mindensity;rho<=(maxdensity/eps);density++){
N = floor(density*volume);
double nodepositions[N][dimension];
// Place nodes in volume (square side L, circle volume *R and obstacle *rob)
for (int i=0;i<N;i++){
int L = 5;
double distancefromorigin;
double x = (L*(rand()/RAND_MAX))-(L/2);
double y = (L*(rand()/RAND_MAX))-(L/2);
distancefromorigin = sqrt((x*x)+(y*y));
if(distancefromorigin<R){
if(distancefromorigin>rob){
nodepositions[i][0] = x;
nodepositions[i][1] = y;
}
}
}
double adjacencymatrix [N][N];
double itzhak; //distance of node 1 from the centre
double isaac; //distance of node 2 from the centre
double vivaldi; //distance between node 1 and node 2
double phi; // a function of the above 3 doubles (see later usage)
double rubicon; // maximum distance nodes within the icecream can be apart before becoming visually indepdendent
double maxtheta; // "in the icecream" means theta < maxtheta
double theta; // angular displacement of inner point from the line bisecting the icecream
// Create adjacency matrix (note alternative implementation using incidence lists)
for (int i=0;i<N;i++){
for (int j=0;j<N;j++){
double x0 = nodepositions[i][0];
double y0 = nodepositions[i][1];
double x1 = nodepositions[j][0];
double y1 = nodepositions[j][1];
itzhak = sqrt(sqr(x0) + sqr(y0));
isaac = sqrt(sqr(x1) + sqr(y1));
vivaldi = sqrt(sqr(x0-x1) + sqr(y0-y1));
phi = ((sqr(vivaldi)+sqr(itzhak)-sqr(isaac))/(2*vivaldi*itzhak));
rubicon = ((itzhak*phi) - sqrt((sqr(rob)) - ((sqr(itzhak))*(1-sqr(phi)))));
maxtheta = asin(rob/itzhak);
theta = acos(phi);
if (x0==x1 && y0==y1){
adjacencymatrix[i][j] = 0;
}
else{
if (isaac<itzhak && theta<maxtheta) {
if (vivaldi>rubicon){
adjacencymatrix[i][j] = 0;}
else {
adjacencymatrix[i][j] = makebond(vivaldi);}
}
else{adjacencymatrix[i][j] = makebond(vivaldi);}
}
}
}
}
FILE *datafc1;
datafc1 = fopen("matrix.dat", "w");
for (int ii = 0; ii<N; ii++){
for (int jj = 0; jj<N; jj++){
int aaa;
aaa = adjacencymatrix[ii][jj];///////////////*******BROKEN LINE******
fprintf(datafc1,"%i", aaa);
}
}
fclose(datafc1);
return 0;
}
/////////////////////////////
////////////////
/////// --End Main--
////////////////
////////////////////////////
int makebond(double x){
// This function takes in the euc. dist. between two nodes and draws a link with prob. H(r)
double randomnumber = (rand()/RAND_MAX); // Random number between 0 and 1
double hr = exp(-beta*sqr(x));// ***Connection function***
int a = 1; // Number to be put into adjacency matrix
if (randomnumber > hr){
a = 0;
}
return a; //Returns 0 or 1 depending on prob. dist.
}
adjacencymatrix is declared in your first for loop, so it's out of scope before the last spot you're using it, in the print-out loop at the bottom.
In addition, you have a useless using namespace std; line. Your code doesn't include any headers that contain std namespace symbols.
Your code in line 57:
double adjacencymatrix [N][N];
is inside a for loop, outside that loop, adjacencymatrix is undefined.
You matrix is defined in the for loop on line 11. Therefore it is out of scope on line 112.
FILE *datafc1;
datafc1 = fopen("matrix.dat", "w");
for (int ii = 0; ii<N; ii++){
for (int jj = 0; jj<N; jj++){
int aaa;
//error adjacencymatrix is declared in your first for loop
aaa = adjacencymatrix[ii][jj];///////////////*******BROKEN LINE******
fprintf(datafc1,"%i", aaa);
}
}