Range function help

Hello,

I am trying to do this exercise for my next C++ class, I read the problem several times and still not sure what is required to do please can someone tell me what is the requirement

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 For this lab exercise, you will write a program with a function named range:
	double range( double x );
range's job is to return the difference between the largest number that has 

been passed to it and the smallest number that has been passed to it.

range needs to remember the largest-so-far, and the smallest-so-far, so you 

will need to use static variables.

Don't declare any global variables in this lab exercise or in the rest of this course.

For instance, if main says
	cout <<range( 1 ) <<", ";
	cout <<range( 4 ) <<", ";
	cout <<range( -2 ) <<", ";
	cout <<range( 3 );
then the program will output
	0, 3, 6, 6
Last edited on
Sounds pretty straight forward to me. What exactly are you not understanding?

The function will have two variables that will be static and are for smallest/largest, they are initialized to "x" the first time the function is called. Then if a number is smaller than smallest it is assigned to smallest. If it is greater than largest it is assigned to largest. Then return the difference( largest - smallest ). I feel like if I provide any more help I would have done the assignment for you.

PS the function is only going to be about 5 lines.

2 for initializing
2 for assigning smallest/largest (I would use ternary operator)
1 for returning difference
Last edited on
You assignment is YOURS.

giblit has provided enough information for you to go ahead.
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
#include <iostream>

using namespace std;

double range(double x);

int main()
{
	cout << range(1)  << ", ";
	cout << range(4)  << ", ";
	cout << range(-2) << ", ";
	cout << range(3)  << ", ";
}

double range(double x)
{
	static double largest, smallest;
	if (x > largest)
		largest = x;
	
	if (x < smallest)
		smallest = x;
	return (largest - smallest);
}

You need to initialize largest and smallest.

so line 17 should be:
1
2
static double largest = x;
static double smallest = x;
Thanks you gilblit
Topic archived. No new replies allowed.