error message

I get an error saying lost in scope dist0 and dist1. I'm lost on where to fix this code. My guess is the functional declaration. Any thoughts?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32


#include <iostream>
#include <iomanip>
using namespace std;

void meet(const double d, const double v0, const double v1, const double &time, const double &distance0, const double &distance1); //Function Declaration goes here


int main(void)
{
	double d, v0, v1, time, distance0, distance1;

	cout << "Enter d, v0, v1: ";
	cin >> d >> v0 >> v1;

	meet(d, v0, v1, time, distance0, distance1);

	cout << fixed << setprecision(3);
	cout << "Time is " << time << " distance0 is " << distance0
		<< " distance1 is " << distance1 << endl;

	return 0;
}


void meet(const double d, const double v0, const double v1, const double &time, const double &distance0, const double &distance1)// First line of the function goes here
{
	time = d / (v0 + v1);
	dist0 = v0 * time;
	dist1 = v1 * time;
}
You never declared dist0 or dist1. In your function parameter, you have defined distance0 and distance1, not dist0 and dist1.
Since the intent is to set values to the arguments passed by reference, they should not be references to const.

Ideally, if we want to const-qualify parameters passed by value, do that only in the definition.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <iomanip>

void meet( double d, double v0, double v1, // passed by value
           double &time, double &distance0, double &distance1 ); // modifiable references
                                                                 // the function would write into these

int main()
{
    double d, v0, v1 ;

    std::cout << "Enter d, v0, v1: ";
    std::cin >> d >> v0 >> v1;

    if( d >= 0 && (v0+v1) > 0 )
    {
        double time, distance0, distance1;
        meet( d, v0, v1, time, distance0, distance1 );

        std::cout << std::fixed << std::setprecision(3)
                  << "Time is " << time << " distance0 is " << distance0
                  << " distance1 is " << distance1 << '\n' ;
    }

    else std::cerr << "invalid input\n" ;
}


void meet( const double d, const double v0, const double v1,
           double &time, double &dist0, double &dist1)
{
    time = d / (v0 + v1);
    dist0 = v0 * time;
    dist1 = v1 * time;
}
Last edited on
Topic archived. No new replies allowed.