Increment function help

I have just started learning c++, and I'm confused on one of my assignments.
Write a void function called increment that will increase the value of the argument passed into it by one.

Our main program should look like this:

1
2
3
4
5
6
7
8
9
10
11
12
int main(){

 

   cout << "Please enter a number: ";
   double n;
   cin >> n;

   cout << "The original number was: " << n << endl;
   
   increment(n);
   cout << "The number after increment is: " << n << endl; 


I have:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void increment(int n)
{
	n++;

}

int main(){

	cout << "Please enter a number: ";
   	double n = 1;
   	

   	cout << "The original number was: " << n << endl;
   
   	increment(n);
   	cout << "The number after increment is: " << n << endl;
} 

It's probably something simple, but any help would be appreciated.
What you want is a reference variable instead of making a local copy of the data in your function.

Check out http://en.wikipedia.org/wiki/Reference_%28C%2B%2B%29#Uses_of_references
Last edited on
Yeah, as @Ganado mentioned, a reference variable is needed.

So your increment function with the reference would just be as follows:

1
2
3
4
void increment(double& n)
{
	n++;
}


Also, you may want to adjust your main so it is exactly like the requirements. Just declare n as a double and cin it.

1
2
3
cout << "Please enter a number: ";
double n;
cin >> n;


Last edited on
Thank you @androidguy1 and @Ganado it works now.
Topic archived. No new replies allowed.