简体   繁体   中英

Variables out of scope in main when called by reference by a function in C++

I have made the following code, whose output should generate a point uniformly at random on the unit circle centered at the origin:

#include "unif.h"
#include <iostream>
#include <cmath>
using namespace std;

void point_on_circle(double& x, double& y)
{
 double r;

do
    {
    double x = unif(-1.,1.);
    double y = unif(-1.,1.);
    double r = x*x + y*y;
    }
    while (r >=1.0);

    x = x / sqrt(r);
    y = y / sqrt(r);
}

int main()
{

 cout << "Pair of points on the circle found is " << x << " and " << y << endl;
 cout << "Let's verify: x^2+y^2=" << x*x+y*y << endl;

    return 0;
}

The header "unif.h" is just a file that contains a function void unif(double x, double y), that produces uniformly random numbers in the interval (x,y), and it works perfectly (already tested). The problem is that when I build the program then it gives me (of course) the error in the main:

"error: 'x' was not declared in this scope"

which is clear since of course x is defined outside the main and never defined in main(). I cannot figure out how to tell the compiler that the values of x and y found by the function point_on_circle should be "carried" inside the main. How could I fix this code? Thanks in advance

In your main method you did not declare a variable called x nor y . Moreover, you also have scoping issues in your point_on_circle(double& x, double& y) function with the variable r .

Please review C++ scoping.

Because you defined x in the do-while loop, so you cannot use it outside the loop, since those definitions hide the parameters x and y. Define it before the loop:

void point_on_circle(double& x, double& y)
{
    double r;

    do
    {
        x = unif(-1.,1.);
        y = unif(-1.,1.);
        r = x*x + y*y;
    }while (r >=1.0);

    x = x / sqrt(r);
    y = y / sqrt(r);
}

You have a few issues. 1) you need to declare x and y inside main. 2) you never, ever actually call point_on_circle. At all. 3) finally, as others noted, you mask parameters x and y in your do loop.

With all of that said, it looks like you're attempting to find a random point on the unit circle. with that in mind, I would remove the do loop entirely and just do this:

void point_on_circle(double& x, double& y)
{
    double r;
    x = unif(-1.,1.);
    y = unif(-1.,1.);
    r = x*x + y*y;
    x = x / sqrt(r);
    y = y / sqrt(r);
}

It gives the exact same result while avoiding a (potential) endless loop, and certainly avoids useless extra processing.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM