How do I properly pass these function values in C++ - c++

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.

Related

C++ function inside function

/*I need to use the result from the (delta) function inside the (sol_ec_II) function for a school assignment.*/
#include <iostream>
#include <ctgmath>
using namespace std;
double delta(double a, double b, double c) {
return (b * b) - (4 * a * c);/* so I need to take this value [(b * b) - (4 * a * c)]
and use it in sol_ec_II in the places where I wrote "delta". */
}
void sol_ec_II(double a, double b, double c) {
if (delta < 0) {//here
cout << endl << "Polinomul NU are solutii.";
}
else {
double x1 = -1 * b - sqrt(delta);//here
double x2 = -1 * b + sqrt(delta);//here
}
}
// I would also need to use the (delta) function inside the (sol_ec_II) so they use the same
a, b, c values like this:
void sol_ec_II(double a, double b, double c) {
delta(a, b, c);
if (delta < 0) {
cout << endl << "Polinomul NU are solutii.";
}
else {
double x1 = -1 * b - sqrt(delta);
double x2 = -1 * b + sqrt(delta);
}
}
//so I don't understand how to get the value that results from delta(a, b, c) and use it inside the if statement and sqrt.
The result "comes out" of the function call at the time you call it. Look, you already know how sqrt works. sqrt is a function! You write sqrt(something) and that calls the function sqrt and it calls the function sqrt with the argument something and then the return value from sqrt gets used in the place where you wrote sqrt(something). e.g. 1 + sqrt(4) calculates 3.
Likewise the return value from delta gets used in the place where you wrote delta(a, b, c). If you want to call delta and then call sqrt (i.e. calculate the square root of the delta) you write sqrt(delta(a, b, c)).
Obviously, just calculating a number is pretty useless. You probably want to do something with the number, like saving it in a variable or printing it. Examples:
cout << "the square root of the delta is " << sqrt(delta(a,b,c)) << endl;
cout << "the delta plus one is " << (delta(a,b,c) + 1) << endl;
double the_delta = delta(a,b,c);
cout << "the delta is " << the_delta << " and the square root of the delta is " << sqrt(the_delta) << endl;
if (delta(a,b,c) < 0)
cout << "the delta is negative" << endl;
else
cout << "the delta isn't negative" << endl;
Note: Every time the computer runs delta(a,b,c) it calls the delta function. It doesn't remember the calculation from last time. You can see this because if you put cout instructions inside the delta function, they get printed every time the computer runs delta(a,b,c).
Of course I will not give you the solution for your program. I hope this helps you understand how functions work.
here you should pass parameters to deleta function in order to execute it:
void sol_ec_II(double a, double b, double c) {
if (delta(a,b,c) < 0) {//here
cout << endl << "Polinomul NU are solutii.";
}
else {
double x1 = -1 * b - sqrt(delta);//here
double x2 = -1 * b + sqrt(delta);//here
}
}
or you could save the result in a new variable called result for example, and after that use it, like that:
void sol_ec_II(double a, double b, double c) {
double result = delta(a,b,c);
if (result < 0) {//here
cout << endl << "Polinomul NU are solutii.";
}
else {
double x1 = -1 * b - sqrt(delta);//here
double x2 = -1 * b + sqrt(delta);//here
}
}
The Same thing for the second function, always to execute a function use parenthesis and pass between them the arguments that the function expects.
To reuse the value you get from calling a function multiple time use a variable:
double delta(double,double,double) { return 1.2; /*ignore this for now*/ }
void sol_ec_II(double a, double b, double c) {
const auto kDelta = delta(a, b, c);
if (kDelta < 0.0) {
// do stuff
} else {
const auto kRootD = sqrt(kDelta); // same idea
const auto x1 = -b - kRootD;
const auto x2 = -b + kRootD;
// use the variables
}
}
I use auto out of habit, you don't need to, double is fine.

sum of series in c++ using if Conditional

am trying to solve the equation in c++ sum of series and am getting the right result
but I just trying to use the if statement to get the same answer of this equation
but always am getting struggling with it
# include <math.h>
#include <iostream>
using namespace std;
int main()
{
double x = 1;
double som = 0;
double lim_nbr = pow(10.0, -6);
int n = 1;
do{
x = 1.0 / ((n*n*4.0 - 1) * n);
som += x;
n+=1;
}while (x >= lim_nbr);
double correctSum = 2.0*log(2.0) -1.0 ;
cout << "Sum = " << som << endl;
cout << "Sumcorrect = " << correctSum << endl;
}
In this case for you to calculate a loop shape using only if, an alternative is to use recursive functions, look at this example:
#include <math.h>
#include <iostream>
using namespace std;
double calc(double lim_nbr, double som, double x, int n)
{
if(x >= lim_nbr || som == 0)
{
x = 1.0 / ((n*n*4.0 - 1) * n);
som += x;
n+=1;
calc(lim_nbr, som, x, n);
}
else
{
return som;
}
}
int main()
{
double lim_nbr = pow(10.0, -6);
/* Call the function with the initial values */
double som = calc(lim_nbr, 0, 1, 1);
cout << "SumWithIf = " << som <<endl;
}
The result you are getting using the do while loop is an approximation to the exact value that you are getting in correctSum. correctSum is the result obtained by adding the series upto infinte terms, however your do while loop calculates only up to a finite number of terms. Therefore the difference of the two values shows up as the error.

No matching function for call to a member function in class

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!

How can I get a function to read the next line of a document everytime it's called?

Really new programmer with a really bad professor here.
I have this code that is supposed to get inputs from a text document (inputsFile) using a function (get_coefficients) and do stuff with it. Currently, everything works perfectly except it reads the same line from the file every time it's executed in the while loop in main. I've google around but I can't find anything that is implementable in my case. I've tried implementing while loops and trying to pass some sort of counting variable but nothing seems to work.
Since this is an assignment for school, I can't do anything fancy. So the more elementary the explanation, the better please, haha. Thank you in advance for any help I get.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
//=======================================FUNCTIONS======================================
//a function that displays instructions
void display_instructions() {
cout << "Enter a, b, c: ";
}
//a function that gathers inputs
void get_coefficients(double& a, double& b, double& c) {
ifstream inputsFile;
string inputs;
string inputString;
inputsFile.open("textinputs.txt");
inputsFile >> a >> b >> c;
cout << a << b << c;
inputsFile.close();
}
//a function that calculates a discriminant
double calc_discriminant(double a, double b, double c) {
double discriminant = (b * b) - (4 * a * c);
return discriminant;
}
//a function that calculates root 1
double calc_root_1(double a, double b, double c, double disc) {
double r1 = ((-b) + (sqrt(disc))) / (2 * a);
return r1;
}
//a function that calculates root 2
double calc_root_2(double a, double b, double c, double disc) {
double r2 = ((-b) - (sqrt(disc))) / (2.0 * a);
return r2;
}
void display(double r1, double r2) {
cout << "the roots are " << r1 << " and " << r2 << "." << endl;
}
//=======================================EXCECUTE=======================================
int main()
{
//while again is true
for (int i = 0; i < 3; i++) {
double a, b, c;
display_instructions();
//run get numbers
get_coefficients(a, b, c);
//if discrimant less than 0 stop the program
if (calc_discriminant(a, b, c) < 0) {
cout << "No real solution" << endl;
}
else { //else get the roots
double disc = calc_discriminant(a, b, c);
double r1 = calc_root_1(a, b, c, disc);
double r2 = calc_root_2(a, b, c, disc);
//print the roots
display(r1, r2);
}
}
}
The problem here is that when you do inputsFile.open() you're opening the file from the start. You should only open the file once so each time you read from it you'll read the next line from where you were the last time. However, the ifstream will be deleted at the end of the scope if you don't save it anywhere. What you can do is initialize the ifstream in main() and then pass it to the function by reference so the ifstream will still be there until the program reaches the end of main.
I think this should work for what you want:
#include <iostream>
#include <fstream>
#include <string>
#include <math.h>
using namespace std;
//=======================================FUNCTIONS======================================
//a function that displays instructions
void display_instructions() {
cout << "Enter a, b, c: ";
}
//a function that gathers inputs
void get_coefficients(double& a, double& b, double& c, ifstream& inputsFile) {
string inputs;
string inputString;
inputsFile >> a >> b >> c;
cout << a << b << c;
}
//a function that calculates a discriminant
double calc_discriminant(double a, double b, double c) {
double discriminant = (b * b) - (4 * a * c);
return discriminant;
}
//a function that calculates root 1
double calc_root_1(double a, double b, double c, double disc) {
double r1 = ((-b) + (sqrt(disc))) / (2 * a);
return r1;
}
//a function that calculates root 2
double calc_root_2(double a, double b, double c, double disc) {
double r2 = ((-b) - (sqrt(disc))) / (2.0 * a);
return r2;
}
void display(double r1, double r2) {
cout << "the roots are " << r1 << " and " << r2 << "." << endl;
}
//=======================================EXCECUTE=======================================
int main()
{
ifstream inputsFile;
inputsFile.open("textinputs.txt");
//while again is true
for (int i = 0; i < 3; i++) {
double a, b, c;
display_instructions();
//run get numbers
get_coefficients(a, b, c, inputsFile);
//if discrimant less than 0 stop the program
if (calc_discriminant(a, b, c) < 0) {
cout << "No real solution" << endl;
}
else { //else get the roots
double disc = calc_discriminant(a, b, c);
double r1 = calc_root_1(a, b, c, disc);
double r2 = calc_root_2(a, b, c, disc);
//print the roots
display(r1, r2);
}
}
inputsFile.close();
}

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