I'm studying C++ beginner book for a while and now I'm learning a function call by reference.
I understand how but I don't understand why....
I solved the problem which is in my book.
Problem: Create a void function called round() that rounds the value of its double argument to the nearest whole value. Have round() use a reference parameter and return the rounded result in this parameter. You can assume that all values to be rounded are positive. Demonstrate round() in a program. Use modf() standard library function.
So. I wrote the following code.
#include <iostream>
#include <cmath>
using namespace std;
void round (double &d);
int main()
{
double userd;
cout <<"Enter a floating value: ";
cin >> userd;
round ( userd );
cout <<"Your floating value rounded up to : " << userd <<"\n";
return 0;
}
void round (double &d)
{
double intpart, fractpart;
fractpart = modf(d, &intpart);
if (fractpart >= 0.5)
d = intpart + 1;
else d = intpart;
}
But it also can write this way(without reference parameter):
#include <iostream>
#include <cmath>
using namespace std;
int round (double d);
int main()
{
double userd;
int i;
cout <<"Enter a floating value: ";
cin >> userd;
i = round ( userd );
cout <<"Your floating value rounded up to : " << i <<"\n";
return 0;
}
int round (double d)
{
double intpart, fractpart;
fractpart = modf(d, &intpart);
if (fractpart >= 0.5)
intpart += 1;
return intpart;
}
The second code is more comfortable for me....
I understand in this case that book want me to practice writing a code for using reference parameter but I don't understand the benefit to use call by reference.
Please explain why I need to know the call by reference method.