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.
void spliceAnyNumber (double anyNumber, int* integerPart, int* fractionalPart), and return the integer part in theintegerPartparameter, and the fractional part in thefractionalPartparameter. It's a common way to "return" more than one value from a function.