Here's what I have:
#include <iostream>
using namespace std;
void test(double &r)
{
r = 0.1;
}
int main() {
double rdefined;
double yo = test(&rdefined);
cout << yo <<endl;
return 0;
}
I've tried putting the test function after the main function and assigning rdefined as 0.0 .
The function declaration void test(double &r)
specifies that the argument is passed by reference not as a pointer. To pass a "pointer-to-double" use: void test(double *r)
.
Although, in practice, the effect is very similar, when passing an argument by reference, you don't explicitly give the address; so, in your code, the call should be as shown below. Also, as noted in the answer given by Vettri , your function does not return a double
value (or, indeed, anything, as it is void
), so you can't assign the variable yo
directly from the call to it.
Try this, as one possible solution:
test(rdefined); // Changes the value of "rdefined"
double yo = rdefined; // Assigns modified value to "yo"
For a discussion on the differences between pointers and references, see here .
Corrected Solution:
#include <iostream>
using namespace std;
double test(double* r)
{
*r = 0.1;
return *r;
}
int main() {
double rdefined;
double yo = test(&rdefined);
cout << yo <<endl;
return 0;
}
You need to specify the correct return value. You got an error because you are expecting a double value in return of your test function, but you declared it as void
.
The only thing you need to do is, to replace & with * in the function parameters. here is the code.
#include <iostream>
using namespace std;
void test(double* r)
{
*r = 0.1;
}
int main() {
double rdefined;
test(&rdefined);
cout << rdefined <<endl;
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.