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!
Related
I posted not long ago on how to compute the sum of Pi with openmp. But it seems something's off with my code. Because manually I get the right result, but when I program it, it gives wrong results, if someone can help me?
PS : s= 1/N
#include <chrono>
#include <iostream>
double f(double x)
{
return (4 / (1 + (x * x)));
}
int main()
{
int i;
const int N = 60;
double s1=0.0; double s2=0.0; double s3=0.0;
double pi = 0.0; double s4=0.0; double s5=0.0;
for (int i=0; i<N; i++)
{
//pi+=((f(i/N)+f((i+1)/N))/2*N);
s1 = f(i/N);
s2 = f((i+1)/N);
s3 = 2 * N;
s4 = s1 + s2;
s5 = s4 / s3;
pi+=s5;
}
printf("Pi = %f",pi);
return 0;
}
The reason the value is different is because variable 'i' as well as 'N' are int's. When dividing int by int the answer will always be int.
Easiest and fastest fix is to change one of the variables to a double eg.:
#include <chrono>
#include <iostream>
double f(double x)
{
return (4 / (1 + (x * x)));
}
int main()
{
const int N = 60;
double s1=0.0; double s2=0.0; double s3=0.0;
double pi = 0.0; double s4=0.0; double s5=0.0;
for (double i=0; i<N; i++) // i changed the int to double for the 'i' declaration
{
//pi+=((f(i/N)+f((i+1)/N))/2*N);
s1 = f(i/N);
s2 = f((i+1)/N);
s3 = 2 * N;
s4 = s1 + s2;
s5 = s4 / s3;
pi+=s5;
}
//printf("Pi = %f",pi);
std::cout << "Pi = " << pi << std::endl;
return 0;
}
Also since you're programming in c++ make sure to pick the better c++ alternative to some of the code:
printf is C. It still works but c++'s cout is a better alternative that's improved and safer in most cases.
You also have an extra unneeded variable declaration. You're creating two 'i' variables. Once at the start and once in the loop.
As I got it from the answers, the problem was in (i/N). Since the i int declared as an int we need to add ((double)i/N).
pi+=((f((double)i/N)+f(((double)i+1)/N))/(2*N));
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
double* cal1(double* all1)
{
int t,count=0;
ifstream srcFile("in.txt", ios::in);
if (!srcFile)
{
cout << "error opening source file." << endl;
return 0;
}
char x;
while (srcFile >> x)
{
t = x - 'a' ;
count++;
if (t >= 0 && t <= 25)
all1[t]++;
else
all1[26]++;
}
all1[27] =count ;
srcFile.close();
/* for (t = 0; t <= 26; t++)
{
cout << all1[t] / all1[27]<<endl;
}
cout << all1[27] << endl;*/
return all1;
}
double finalcal1(double* all)
{
int t;
double p,cal1=0;
for (t = 0; t <= 26; t++)
{
p = (all[t] / all[27]);
all[t] = p * log(p);
}
for (t = 0; t <= 26; t++)
{
cal1 -= all[t];
}
return cal1;
}
int main()
{
double *all =new double[28]; //1
double t;
all = cal1(all);
t = finalcal1(all);
cout << t << endl;
delete[] all;
return 0;
}
enter code here
instead of receiving a number from the result, I just got a “-nan.(ind)” which is not even a number. Besides, when I change the number from mark 1 to *all =new double[27] which is what it supposed to be, there would be error or bugs showing up.
double *all =new double[28];
You probably want to initialise all these values to zero to start with since, otherwise, they'll have arbitrary values.
And, if those arbitrary values consist of any NaN items, that will propagate when you add things to them, or divide by some count.
Something like this will do the trick:
double *all = new double[28]();
You may also want to consider the possibility that log(x) is not actually defined for all values of x (such as zero or negative values) - that may be another way in which you could get a NaN.
I'm trying to write a very simple C++ program which outputs a lookup table with the corresponding x and y values of sinus function. The code that I wrote is the following:
#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double hw = 4.0;
int nsteps = 30;
const double PI = 3.14159;
const double maxx = hw * PI;
const double deltax = maxx / nsteps;
double x = 0.0;
for (int i = 0; i < nsteps; i++) {
const double f = sin(x);
cerr << x << "\t" << f << endl;
x = x + deltax;
}
return 0;
}
Now the program is working, but my problem is, that the values are not getting aligned properly as showed in the following picture
So is there any way, to achieve that the second column of the values will actually be a column and all the values are aligned at the same position? What could I use instead of \t?
The above answer provides an incorrect solution because the alignment is not set correctly. I would use a function to handle the formatting:
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
void printxy(double x, double y, int width){
cout << setw(width) << x << "\t";
if (y < 0) cout << "\b";
cout << setw(width) << y << "\n";
}
int main(){
double hw = 4.0;
int nsteps = 30;
const double PI = 3.14159;
const double maxx = hw * PI;
const double deltax = maxx / nsteps;
double x = 0.0;
int decimals = 6;
int width = 8; //Adjust as needed for large numbers/many decimals
cout << std::setprecision(decimals);
cout << std::setw(width);
cout.setf(ios::left);
for (int i = 0; i < nsteps; i++) {
const double y = sin(x);
printxy(x, y, width);
x = x + deltax;
}
}
The output is now formatted correctly:
0 0
0.418879 0.406736
0.837757 0.743144
1.25664 0.951056
1.67551 0.994522
2.09439 0.866026
2.51327 0.587787
2.93215 0.207914
3.35103 -0.207909
3.76991 -0.587783
4.18879 -0.866024
4.60767 -0.994521
5.02654 -0.951058
5.44542 -0.743148
5.8643 -0.406741
6.28318 -5.30718e-06
6.70206 0.406731
7.12094 0.743141
7.53982 0.951055
7.95869 0.994523
8.37757 0.866029
8.79645 0.587791
9.21533 0.207919
9.63421 -0.207904
10.0531 -0.587778
10.472 -0.866021
10.8908 -0.994521
11.3097 -0.951059
11.7286 -0.743151
12.1475 -0.406746
I would also discourage the use of cerr for these kinds of printing operations. It is intended for printing errors. Use cout instead (it works the same way for all practical purposes).
I should also mention that endl is a ticking bomb: it flushes the output, meaning that the internal buffer of the stream is written out (be it the console, a file or whatever). When applications scale and become more IO intensive, this can become a significant performance problem: the buffer that is intended to increase the IO performance is potentially unused due to frequent endl insertions. The solution is to use the newline character '\n'.
Use std::setprecision() to set count number for decimal after point, and std::setw() to set width of output length. Include <iomanip> needed, example:
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
double hw = 4.0;
int nsteps = 30;
const double PI = 3.14159;
const double maxx = hw * PI;
const double deltax = maxx / nsteps;
double x = 0.0;
cerr << std::setprecision(8);
for (int i = 0; i < nsteps; i++) {
const double f = sin(x);
cerr << std::setw(20) << x << std::setw(20) << f << endl;
x = x + deltax;
}
return 0;
}
Output is:
0 0
0.41887867 0.40673632
0.83775733 0.74314435
1.256636 0.95105619
1.6755147 0.99452204
2.0943933 0.86602629
2.513272 0.58778697
2.9321507 0.20791411
3.3510293 -0.20790892
3.769908 -0.58778268
4.1887867 -0.86602363
//...
I am trying to write a program using functions that calculates county tax, sales tax, adds them together, and outputs them in main. I have also made a printData function so I could output everything at once but i'm confused on how to use it, because of an initialization error in run time. I am not very good with function and was hoping I could get some help.
Here is my written code: (updated)
#include <iostream>
using namespace std;
void calcCounty(double &TotalSales, double &CountySalesTax);
void calcState(double &TotalSales, double &StateSalesTax);
void calcTotal(double &TotalSales, double &CountySalesTax, double &StateSalesTax);
void printData(double &TotalSales, double &CountySalesTax, double &StateSalesTax);
double TotalSales;
double CountySalesTax;
double StateSalesTax;
int main()
{
cout << "Tax Calculation program" << endl;
cin >> TotalSales;
printData(TotalSales, CountySalesTax, StateSalesTax);
cout << TotalSales << CountySalesTax << StateSalesTax;
return 0;
}
void calcCounty(double &TotalSales, double &CountySalesTax)
{
CountySalesTax = TotalSales * 0.4;
}
void calcState(double &TotalSales, double &StateSalesTax)
{
StateSalesTax = TotalSales * 0.2;
}
void calcTotal(double &TotalSales, double &CountySalesTax, double &StateSalesTax)
{
TotalSales = CountySalesTax + StateSalesTax;
}
void printData(double &TotalSales, double &CountySalesTax, double &StateSalesTax)
{
cout << TotalSales, CountySalesTax, StateSalesTax;
}
Why don't you rather return a value from your functions?
double calcCounty(double& totalSales) {
return totalSales * 0.4;
}
Then in your main do:
countySalesTax = calcCounty(totalSales);
You need to initialize your variables first (the ones you need).
For example, this function:
void calcCounty(double &TotalSales, double &CountySalesTax)
{
CountySalesTax = TotalSales * 0.4;
}
should have TotalSales initialized before been called.
As suggested by the comments, you also need to call the functions at some point.
Moreover, the printing should be done like this in your case:
cout << TotalSales << ", " << CountySalesTax << ", " << StateSalesTax;
First, I would suggest you to read this example:
#include <iostream>
using namespace std;
/*
* Write a program, which will declare two variables, 'a' and 'b'.
* They will be initialized with the values 10 and 100, respectively.
* Write a function 'int find_min(int a, int b)`, which will find
* which of the given parameters is less and will return it.
*
* Then, write `void find_min_no_return(int a, int b, int& min)`,
* which will do the same job as `find_min()`, but with no return
* statement.
*/
int find_min(int a, int b) {
if(a < b) {
return a;
}
else {
return b;
}
}
/*
* 'min' is passed by reference because it is
* going to be modified. 'a' and 'b' are passed
* by value.
*/
void find_min_no_return(int a, int b, int& min) {
if(a < b) {
min = a;
}
else {
min = b;
}
}
int main() {
int a = 10;
int b = 100;
int min;
min = find_min(a, b);
cout << "min of first function called = " << min << endl;
find_min_no_return(a, b, min);
cout << "min of second function called = " << min << endl;
return 0;
}
and then solve your problem.
i wrote a code that calculates and outputs a difference between the sum of the squares of the first ten natural numbers and the square of the sum.
The problem is with function squareOfSum(). The function should return 3025 but it always returns 3024. Even if i try to put 100 into brackets i get 25502499 (25502500 is correct). No matter what number i put into brackets i always get the same problem.
What am I doing wrong?
Here's a screenshot of my output.
#include <iostream>
#include <cmath>
using namespace std;
int sumOfSquares(int limit);
int squareOfSum(int limit);
int main()
{
cout << sumOfSquares(10) << endl;
cout << squareOfSum(10) << endl;
cout << squareOfSum(10) - sumOfSquares(10) << endl;
}
int sumOfSquares(int limit)
{
int sum = 0;
for(int i = 1; i<=limit; i++)
{
sum +=pow(i,2);
}
return sum;
}
int squareOfSum(int limit)
{
int sum = 0, square = 0;
for(int i = 1; i<=limit; i++)
{
sum +=i;
}
square = pow(sum,2);
return square;
}
Note that pow is a function that works with floating point numbers. Optimizations might lead to rounding errors or truncation during implicit coversion to int. Replace pow(i, 2) with i*i and you'll get pure integer arithmetic and thus exact results.
#include <bits/stdc++.h>
#include <algorithm>
using namespace std;
int main()
{
int higher_limit = 100;
int SquaresOfSum = 0;
int SumOfSquares = 0,count=0;
for(int i=1;i<=higher_limit;i++){
count += i;
SumOfSquares += pow(i,2);
}
SquaresOfSum = pow(count,2);
cout<<SquaresOfSum-SumOfSquares;
}
Using Javascript
const sumSquareDifference = (n) => {
const numbers = [...Array(n + 1).keys()];
const sumOfSquares = numbers.reduce((accumulator, number) => accumulator + (number ** 2));
const squareOfSum = numbers.reduce((accumulator, number) => accumulator + number) ** 2;
return squareOfSum - sumOfSquares;
}
console.log(sumSquareDifference(10));