c++ passing pointers to a function - c++

I am trying to create a console app in C++ that prompts the user to enter a floating point number and then takes that number and separates out the integer part and the fraction part.
Example output would be:-
Please enter a floating point number:
800.589
The integer part is 800 and the fraction part is .589
My solution is shown below:
#include <iostream>
#include <cmath>
using namespace std;
void spliceAnyNumber (double anyNumber)
{
double integerPart = 1;
double fractionPart = 1;
double *pIntegerPart = &integerPart;
double *pFractionPart = &fractionPart;
fractionPart = fmod(anyNumber,1);
integerPart = anyNumber - fractionPart;
cout << "The integer part is " << *pIntegerPart << " and the fraction part is " << *pFractionPart << "\n";
cout << endl;
cout << "The address of *pIntegerPart is " << &integerPart << "\n";
cout << endl;
cout << "The address of *pFractionPart is " << &fractionPart << "\n";
cout << endl;
}
int main()
{
cout << "Please enter a floating point number: ";
double anyNumber = 0;
cin >> anyNumber;
cout << endl;
spliceAnyNumber(anyNumber);
system("Pause");
return 0;
}
I wrote the program but I am also being asked to pass pointers to the function and manipulate the dereferenced values. I tried to do that below but I am getting a bunch of errors back from the compiler.
#include <iostream>
#include <cmath>
using namespace std;
void spliceAnyNumber (double *pAnyNumber)
{
double integerPart = 1;
double fractionPart = 1;
double *pIntegerPart = &integerPart;
double *pFractionPart = &fractionPart;
&fractionPart = fmod(&anyNumber,1);
&integerPart = &anyNumber - &fractionPart;
cout << "The integer part is " << *pIntegerPart << " and the fraction part is " << *pFractionPart << "\n"; *pFractionPart << "\n";
cout << endl;
cout << "The address of *pIntegerPart is " << &integerPart << "\n";
cout << endl;
cout << "The address of *pFractionPart is " << &fractionPart << "\n";
cout << endl;
}
int main()
{
cout << "Please enter a floating point number: ";
double *pAnyNumber = &anyNumber;
cin >> *pAnyNumber;
cout << endl;
spliceAnyNumber(*pAnyNumber);
system("Pause");
return 0;
}
Where am I going wrong with adding in pointers? Version 1 works but version 2 does not.

I've notated this inline.
#include <iostream>
#include <cmath>
using namespace std;
void spliceAnyNumber (double *pAnyNumber)
{
double integerPart = 1;
double fractionPart = 1;
double *pIntegerPart = &integerPart;
double *pFractionPart = &fractionPart;
&fractionPart = fmod(&anyNumber,1); // <- you should dereference pAnyNumber instead, and assign to fractionPart (i.e. "fractionPart = fmod(*pAnyNymber, 1);
&integerPart = &anyNumber - &fractionPart; // <- similar as above
cout << "The integer part is " << *pIntegerPart << " and the fraction part is " << *pFractionPart << "\n"; *pFractionPart << "\n";
cout << endl;
cout << "The address of *pIntegerPart is " << &integerPart << "\n";
cout << endl;
cout << "The address of *pFractionPart is " << &fractionPart << "\n";
cout << endl;
}
int main()
{
cout << "Please enter a floating point number: ";
double *pAnyNumber = &anyNumber; // <- you haven't declared an 'anyNumber' variable to take the address of
cin >> *pAnyNumber;
cout << endl;
spliceAnyNumber(*pAnyNumber);
system("Pause");
return 0;
}

The & operator takes the address of a variable, so typeof(&anyNumber) == double**. You want the * operator instead.
You should read double *pAnyNumber as "When I apply the * operator, I get a double". (You actually get an lvalue reference, but that doesn't roll off the tongue and will probably confuse you...)
Your main function is a mess; leave it the same as the original and change spliceAnyNumber(pAnyNumber); to spliceAnyNumber(&pAnyNumber);.

I assume when you wrote anyNumber you actually meant pAnyNumber. If you have a pointer
double* p;
You dereference by *p, not &p. The former gives you a double while the latter gives you a double**.

You have to declare anyNumber before you can dereference it:
double *pAnyNumber = &anyNumber; // references an undeclared variable
Just take the address when passing to the function. Before that, you can use normal variables - no need for pointers:
double anyNumber;
cin >> anyNumber;
cout << endl;
spliceAnyNumber(&anyNumber);
Additionally, you're using the wrong operator in your function. It should be like this:
*pFractionPart = fmod(*pAnyNumber,1);
*pIntegerPart = *pAnyNumber - fractionPart;
The other thing is invalid syntax: &variable = ... literally means "address of variable = ", which results in a double**.
So the only change you have to make is the function parameter, and accessing it. No need for all those pointers inside the function..

Related

Issue with functions not returning values

I am trying to create a program where you enter two values in individual functions and then print them out in the main function. But I am having an error stating that my function is not returning values.
#include <iostream>
#include <iomanip>
using namespace std;
void welcome();
double mass(double m);
double freqnat(double nf);
int main()
{
double attachedmass = 0;
double naturalfrequency = 0;
welcome();
mass(attachedmass);
freqnat(naturalfrequency);
cout << attachedmass << setw(20) << naturalfrequency << endl;
}
void welcome()
{
cout << "Welcome to the spring stiffness program." << endl << endl << "This program calculates spring stiffness using mass and natural frequency to calculate your spring stiffness." << endl << endl;
system("pause");
cout << endl;
}
double mass(double m)
{
cout << "Please enter your desired mass." << endl << endl;
cin >> m;
}
double freqnat(double nf)
{
cout << "Please enter your desired natural frequency." << endl << endl;
cin >> nf;
}
I tried using return m; and return nf; at the end of the functions, hoping this would tell the function to return the values inputted by the user. Instead, the program does run but the values print out as zeroes.
You need to return values AND store them somewhere:
// storing results in variables
attachedmass = mass(attachedmass);
naturalfrequency = freqnat(naturalfrequency);
Your functions should be:
double mass(double m)
{
cout << "Please enter your desired mass." << endl << endl;
cin >> m;
return m;
}
double freqnat(double nf)
{
cout << "Please enter your desired natural frequency." << endl << endl;
cin >> nf;
return nf;
}
Having said this, you don't need to pass any parameters at all to the functions for this. They can be something like this:
#include <iostream>
#include <iomanip>
using namespace std;
void welcome()
{
cout << "Welcome to the spring stiffness program." << endl << endl << "This program calculates spring stiffness using mass and natural frequency to calculate your spring stiffness." << endl << endl;
cout << endl;
}
double mass()
{
double user_in;
cout << "Please enter your desired mass." << endl << endl;
cin >> user_in;
return user_in;
}
double freqnat()
{
double user_in;
cout << "Please enter your desired natural frequency." << endl << endl;
cin >> user_in;
return user_in;
}
int main()
{
double attachedmass = 0;
double naturalfrequency = 0;
welcome();
attachedmass = mass();
naturalfrequency = freqnat();
cout << attachedmass << setw(20) << naturalfrequency << endl;
}
So with youre program you are using the functions but you are not assigning the return value to anything so the two double values will not change, you will probably want to pass the doubles in by reference like this:
double mass(double& m);
and
double freqnat(double& nf);
Before you werent changing the two double values atall so they would not change but now you are passing them by reference which means you can change them.
Also you will not need to return anything so you can just make mass and freqnat's return type void as you just passed a reference to it. So the working program would be:
#include <iostream>
#include <iomanip>
using namespace std;
void welcome();
double mass(double m);
double freqnat(double nf);
int main()
{
double attachedmass = 0;
double naturalfrequency = 0;
welcome();
mass(attachedmass);
freqnat(naturalfrequency);
cout << attachedmass << setw(20) << naturalfrequency << endl;
}
void welcome()
{
cout << "Welcome to the spring stiffness program." << endl << endl << "This program calculates spring stiffness using mass and natural frequency to calculate your spring stiffness." << endl << endl;
system("pause");
cout << endl;
}
void mass(double& m)
{
cout << "Please enter your desired mass." << endl << endl;
cin >> m;
}
void freqnat(double& nf)
{
cout << "Please enter your desired natural frequency." << endl << endl;
cin >> nf;
}

Calculating Cash On Cash Returning 0 for the result

I am creating a class function where it returns Cash on Cash return which gives you a percentage and is a key indicator to see if you are getting a good ROI. I created the function, but for some reason its not giving me the answer I want which is "3%" or "50%. Cash On Cash return is usually (yearly cash flow / total cash invested ). It is just returning 0.
double cashOnCashReturn(int cashFlowMonthly, int buyingPrice, double downPaymentP, double closingCost, int repairs) {
int fullMonth = 12;
int yearlyCashFlow = cashFlowMonthly * fullMonth;
double downPaymentPercentage = downPaymentP/100;
int downPaymentCashInvested = downPaymentPercentage * buyingPrice;
long closingCostTotal = closingCost * buyingPrice;
int cashInvestment = downPaymentCashInvested + repairs + closingCostTotal;
double cashOnCash = (yearlyCashFlow / cashInvestment) * 100;
cout << fixed << setprecision(0);
return cashOnCash;
}
My main function is below
int main()
{
string address;
int buyingPrice;
int rent;
int cashFlowMonthly;
int downPayment;
double closingCostPercent = 0.05;
int repairCost;
// Mortgage Calculator Variables
// double annualInterestRate;
// double loanAmount;
// double monthlyInterestRate;
// double numberOfPayments;
// double totalPayBack;
// double monthlyPayment;
cout << "Address: ";
getline(cin,address);
cout << "Buying Price: ";
cin >> buyingPrice;
cout << "Down Payment Percentage: ";
cin >> downPayment;
std::cout << "Repair Cost: ";
std::cin >> repairCost;
cout << "Rent Monthly: ";
cin >> rent;
std::cout << "Cashflow Monthly: ";
std::cin >> cashFlowMonthly;
realEstate firstHome;
firstHome.setAddress(address);
firstHome.setBuyingPrice(buyingPrice);
firstHome.setRent(rent);
std::cout <<"\n";
std::cout << "================================================" << std::endl;
std::cout << "Real Estate Calculator Created By Austin Nguyen" << std::endl;
std::cout << "================================================" << std::endl;
std::cout << "Address: " << firstHome.getAddress() << std::endl;
std::cout << "\n";
std::cout << "Buying Price: " << firstHome.getBuyingPrice() << std::endl;
std::cout << "\n";
std::cout << "Rent: " << firstHome.getRent() << std::endl;
std::cout << "\n";
std::cout << "Does It Pass One Percent Rule? " << firstHome.onePercentRule(buyingPrice,rent) << std::endl;
std::cout << "\n";
std::cout << "Cash On Cash Return: " << firstHome.cashOnCashReturn(cashFlowMonthly,buyingPrice,downPayment,closingCostPercent,repairCost);
std::cout << "\n";
std::cout << "================================================" << std::endl;
std::cin.clear();
yearlyCashFlow and cashInvestment are integers. Dividing two integers results in an integer - even if assigning the result to a double.
ala double y = 3 / 5 results in y being assigned zero because 3/5 is an integer expression that gets evaluated as 0 instead of .6.. However 3/5.0 is a floating point expression.
So this line:
double cashOnCash = (yearlyCashFlow / cashInvestment) * 100;
Should really be:
double cashOnCash = (yearlyCashFlow / (double)cashInvestment) * 100;
By casting one element in the division expression from int to double results in the the entire expression evaluated as a floating point expression.

cin.get() causing "no instance of overloaded function" error

I'm having a bit of issues with a C++ Project that I'm working on for a class. I keep getting an error message stating 'no instance of overloaded function'. I did some googling and it seems that everyone says that this error is caused by passing a string into the cin.get() function, but I'm using this function with a char, not a string. Visual Studio says the error is at: "cin.get(nameFull);" but I've defined nameFull as a char, not a string. Any help would be greatly appreciated, thank you for your time.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const int MONTHS = 12;
const int RETRO_MONTHS = 6;
char nameFull[30]; // INPUT - Employee's full name
float salaryCurrent; // INPUT - Current annual salary
float percentIncrease; // INPUT - Percent increase due
float salaryNew; // OUTPUT - New salary after increase
float salaryMonthly; // OUTPUT - New monthly salary
float retroactivePay; // OUTPUT - Retroactive pay due employee
int count; // CALC - Counter for loop
for (int count = 0; count < 3; count++) {
cout << "What is your name?" << endl;
cin.get(nameFull);
cout << "What is your current salary?" << endl;
cin >> salaryCurrent;
cout << "What is your pay increase?" << endl;
cin >> percentIncrease;
salaryNew = salaryCurrent + (salaryCurrent * percentIncrease);
salaryMonthly = salaryNew / MONTHS;
retroactivePay = (salaryNew - salaryCurrent) * RETRO_MONTHS;
cout << nameFull << "'s SALARY INFORMATION" << endl;
cout << "New Salary"
<< setw(20) << "Monthly Salary"
<< setw(20) << "Retroactive Pay" << endl;
cout << setprecision(2) << fixed << setw(10) << salaryNew
<< setw(20) << salaryMonthly
<< setw(20) << retroactivePay << endl;
cout << "<Press enter to continue>" << endl << endl;
cin.get();
}
return 0;
}
nameFull is an array of char (more specifically char[30]) which decays to a pointer to character (char*). There is no overload of std::istream::get which accepts a single pointer to character, but there is one that accepts a pointer + the size of the buffer that you would like to read into.
So all you need to do is pass an additional parameter:
cin.get(nameFull, 30);

How to return a variable from one function in C++ to main then use it in another function?

Okay so I have a calorie calculator that is supposed to be separated into the five functions including main seen below. My issue is that I get a compiler error because the variables from the inputNumber function and calculateCalories function cannot be read by any of the other functions once they are obtained. I am not allowed to use Global variables. There must be something I am missing to be able to read the variables within the main function then output them into the other functions to get the proper output. Any help would be appreciated.
Here is the code as it stands:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
int Lbs, hourr, hourW, hourWe, hourb;
double calBad, calRun, calWal, calWei;
string name;
cout << "Welcome to Megan McCracken's Workout Calculator!" << endl;
cout << endl;
cout << "Please enter your name: ";
getline(cin, name);
inputNumber(Lbs, hourr, hourW, hourWe, hourb);
calculateCalories(Lbs,hourr,hourb,hourW,hourWe,calBad,calRun,calWal,calWei);
displayHeadings(name);
displayLine(hourr,hourb,hourW,hourWe,calBad,calRun,calWal,calWei);
system("pause");
return 0;
}
int inputNumber(int Lbs, int hourr, int hourb, int hourW, int hourWe)
{
cout << "Please enter your weight: ";
cin >> Lbs;
return Lbs;
cout << "Please enter the minutes spent playing badminton: ";
cin >> hourb;
return hourb;
cout << "Please enter the minutes spent running: ";
cin >> hourr;
return hourr;
cout << "Please enter the minutes spent walking: ";
cin >> hourW;
return hourW;
cout << "Please enter the minutes spent lifting weights: ";
cin >> hourWe;
return hourWe;
cout << endl;
}
double calculateCalories(int Lbs, int hourW, int hourb, int hourr, int hourWe, double calBad, double calRun, double calWal, double calWei)
{
const double Badburn = .044, Runburn = .087, Walkb = .036, Weightb = .042;
double calBad, calRun, calWal, calWei;
calBad = (Badburn * Lbs) * hourb;
calRun = (Runburn * Lbs) * hourr;
calWal = (Walkb * Lbs) * hourW;
calWei = (Weightb * Lbs) * hourWe;
return calBad;
return calRun;
return calWal;
return calWei;
}
void displayHeadings(string name)
{
cout << "Here are the results for " << name << ": " << endl;
cout << endl;
cout << "Activity" << right << setw(18) << "Time" << right << setw(10) << "Calories" << endl;
cout << "--------------------------------------" << endl;
}
void displayLine(int hourb,int hourr, int hourW, int hourWe, double calBad, double calRun, double calWal, double calWei)
{
int HB, MB, HR, MR, HW, MW, HWE, MWE, Hour, Min;
double Calorie;
HB = (hourb / 60);
MB = (hourb % 60);
HR = (hourr / 60);
MR = (hourr % 60);
HW = (hourW / 60);
MW = (hourW % 60);
HWE = (hourWe / 60);
MWE = (hourWe % 60);
Calorie = calBad + calRun + calWal + calWei;
Hour = (hourb + hourr + hourW + hourWe) / 60;
Min = (hourb + hourr + hourW + hourWe) % 60;
cout << "Badminton" << right << setw(14) << HB << ":" << setfill('0') << setw(2) << MB << setfill(' ') << right << setw(10) << setprecision(3) << fixed << showpoint << calBad << endl;
cout << resetiosflags(ios::fixed | ios::showpoint);
cout << "Running" << right << setw(16) << HR << ":" << setfill('0') << setw(2) << MR << setfill(' ') << right << setw(10) << setprecision(3) << fixed << showpoint << calRun << endl;
cout << resetiosflags(ios::fixed | ios::showpoint);
cout << "Walking" << right << setw(16) << HW << ":" << setfill('0') << setw(2) << MW << setfill(' ') << right << setw(10) << setprecision(3) << fixed << showpoint << calWal << endl;
cout << resetiosflags(ios::fixed | ios::showpoint);
cout << "Weights" << right << setw(16) << HWE << ":" << setfill('0') << setw(2) << MWE << setfill(' ') << right << setw(10) << setprecision(3) << fixed << showpoint << calWei << endl;
cout << "--------------------------------------" << endl;
cout << resetiosflags(ios::fixed | ios::showpoint);
cout << "Totals" << right << setw(17) << Hour << ":" << setfill('0') << setw(2) << Min << setfill(' ') << right << setw(10) << setprecision(3) << fixed << showpoint << Calorie << endl;
cout << endl;
}
If you want to modify passed-in variables within a function in C++, you should be passing them in by reference (default is by value, meaning you get a copy of the variable which is effectively thrown away when the function exits).
So, by way of example:
void xyzzy (int plugh) { plugh = 42; }
int main() {
int twisty = 7;
xyzzy (twisty);
cout << twisty << '\n';
return 0;
}
will output 7 because twisty was passed by value and changes to it within the function will not be echoed back to the caller.
However, if you pass by reference with:
void xyzzy (int &plugh) { plugh = 42; }
// ^
// This does the trick.
then you'll find it outputs 42 as desired.
For your particular case, you want to look at the variables in the argument list of inputNumber:
int inputNumber(int Lbs, int hourr, int hourb, int hourW, int hourWe)
Any of these that you want echoed back to the caller (and that looks like all of them from a cursory glance) should be pass by reference rather than pass by value.
You should also look into calculateCalories as well, since that is doing the same thing. Keep in mind that only the ones you want to change and echo back to the caller need to be pass-by-reference. So that's only the ones starting with cal.
And, since you're using the pass-by-reference to modify the variables, there's absolutely no reason to return anything from that function so it can be specified as void calculateCalories ... and the return statements removed (in any case, only the first return would have actually done anything, the others would have been unreachable code).
If you haven't yet got to the point where you can use references in your classwork (as seems to be indicated by one of your comments), you can do what C coders have been doing for decades, emulating pass-by-reference with pointers. In terms of the simplified example above, that would mean modifying the function to receive a pointer to the item you want changed, changing what it points to, and calling it with the address of the variable to be changed:
void xyzzy (int *pPlugh) { *pPlugh = 42; }
int main() {
int twisty = 7;
xyzzy (&twisty);
cout << twisty << '\n';
return 0;
}
However, it's a poor substitute for the real thing and, if your educator is trying to teach you that, it's the same as if they're getting you to use printf/scanf rather than cout/cin for user I/O: it's certainly possible in C++ since the language includes legacy C stuff, but it's not really teaching you the C++ way.
People who claim to be C++ developers but really code in C using a C++ compiler, are a rather strange breed that I like to call C+ developers - they've never really embraced the language properly. The sooner people put aside the legacy stuff, the better they'll be as C++ developers.
Pass the variables by references. Then the functions will be able to edit them.
Your other solution (not so much of a good idea but still working) is to create a struct/class and make the functions return it.
P.S. Your code won't work if the functions are in this order unless you add their signatures in the beginning:
int main();
int inputNumber(int,int,int,int,int);
//and so on
In input number, you can not use 'return' to return each value - it will do the first return statement.
In C++ you can use pass by reference so that values assigned to the variables will be passed back up.
In this case, via the input variables would be inputNumber so use '&' to denote the vaiables are references:
void inputNumber(int &Lbs, int &hourr, int &hourb, int &hourW, int &hourWe)
{
.
.
.
}
Similar idea for calculateCalories, get rid of the returns:
void calculateCalories(int Lbs, int hourW, int hourb, int hourr, int hourWe, double &calBad, double &calRun, double &calWal, double &calWei)
{
.
.
}
Note that we are only bothering to pass to reference for the variables that we will be passing back.

1.#QNAN error C++

I am new to programming and trying to write a new program. While checking through my program it is returning the error code 1.#QNAN. I have tried isolating the variable and researching for answers but cannot find any solutions.
My code:
// This is a program to decide what culvert should be properly used for a specific installation
// using given measurements and data
//
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
// initializing functions
double slope_function();
double cbasin();
// initializing classes: Subdivisions specs
//intitializing global variables
double edge_road =0;
double up_stream =0;
double down_stream =0;
double tbm =0.0;
//double culv_length =0;
double slope = 0.0 ;
char street_name[1001];
int min_culv = 15;
double up_strm_culv =0;
double dwn_strm_culv =0;
int main (int nNumberofArgs, char* pszArgs[])
{
cout<< "This program will allow the surveyor to double check their calculations\n";
cout << "in deciding what size, type, and requirements are allowed for the\n";
cout << "installation of culverts in Terrebonne Parish.\n\n";
// begin input
cout << "what is the name of the street\nwhere the culverts will be installed: ";
cin.getline (street_name,1000);
cout << endl;
cout << "What is the Benchmark: ";
cin >> tbm;
cout << endl;
cout << "What is the elevation of the edge of the road: ";
cin >> edge_road;
cout << endl;
cout << "What is the up-stream culvert size: ";
cin >> up_strm_culv;
cout << endl;
cout << "What is the culverts up-stream inverted elevation: ";
cin >> up_stream;
cout << endl;
cout << "What is the down-stream culvert size: ";
cin >> dwn_strm_culv;
cout << endl;
cout << "What is the culverts down-stream inverted elevation: ";
cin >> down_stream;
cout << endl;
cout << "What is the length of culvert requested: ";
cin >> culv_length;
cout << "Your slope is : ";
cout << slope_function();
cout << endl;
cout << street_name;
cout << endl;
cout << cbasin();
cout << endl;
// wait until user is ready before terminating program
// to allow the user to see the program results
system ("pause");
return 0;
}
// slope function
double slope_function()
{
double riseoverrun = 0.0;
slope = (up_stream - down_stream)/ culv_length;
return slope;
}
// Catch Basin function
double cbasin ( )
{
double cb = 0;
cb = culv_length / 60;
cout << endl;
cout << "You need ";
cout << cb;
cout << " catch basins for this job.";
cout << endl;
}
1#QNAN is a string representation for a "quiet NAN". A "NAN" is "not-a-number" and applies only to floats and doubles.
NANs can be very useful actually for representing "null" values (rather than picking some genuine number and hoping for the best you don't need that number for its natural meaning).
Some mathematical operations can return a NAN if the operation is "not valid" (eg taking the log of a negative number).
You can generate a QNAN from C++ using
double d = std::numeric_limits<double>::quiet_NaN();
Any comparison operation (==, <= etc) on a NAN returns false, even comparing its equality to itself, except for != which always returns true (even when comparing to itself).
(The actual bug in your code appears to be a function that returns double but has no return statement).