How to increase the reference variable by 1

I am new to C ++, and I try to increase the number of cars starting at 50, but only increase by one if you damage more than cardamom. I want cars to keep their value the next time this happens through a cycle. Hope this makes sense.

int Power (int &car); int main(){ int car = 50; // ... // ... // ... int carDamage = 0; int yourDamage = 0; // pick a random number between 1 to 50 yourDamage = 0 + rand() % (50 - 0 + 1); carDamage = 0 + rand() % (50 - 0 + 1); cout << "You hit the car and cause damage of: " << carDamage << endl; cout << "The car hits you and causes damage of: " << yourDamage << endl; cout << endl; if(carDamage < yourDamage) { cout << "You win" << endl; cout << "You gain strength." << endl; cout << endl; int car = car + 1; } else { 
+6
source share
6 answers

You declare a new variable that obscures the original.

change

 int car = car + 1; 

to

 car = car + 1; 
+8
source

You need to reassign the same variable. You are declaring a new variable.

Change this:

 int car = car + 1; 

For this:

 ++car; 
+7
source

By doing this:

 int car = car + 1; 

You redefine the car as an integer.

cm

 #include <stdio.h> int car; int main() { car = 0; for (int i = 0; i < 10; i++) { int car = 0; car++; } printf("%3d", car); } 

against

 #include <stdio.h> int car; int main() { car = 0; for (int i = 0; i < 10; i++) { car++; } printf("%3d", car); } 
+1
source

You declare a new car variable inside the if statement, which hides the original car variable from the specified scope. Deleting a type will allow you to reference an existing variable instead of declaring a new one.

In short, change

 int car = car + 1; 

to

 car = car + 1; 
0
source

Your problem is that when you say

 int car = car + 1; 

Basically you create a local variable called car (local for the if statement), which is set to 51 (since the original local area variable (local to main) contains 50 and you add 1). This local variable (included in the if statement) is destroyed as soon as you exit the if statement.

If you change it to

 car = car + 1; 

Now you change the local variable to main, and therefore the update will be saved.

0
source

I don't see the loop, but I'm going to fear that your problem is that you are doing this line:

 int car = car + 1; 

in your:

 if(carDamage < yourDamage) 

which means that you update your resource every time by resetting its value.

write int car; regardless of the operator and just ++car; inside the loop in which you originally wrote int car = car + 1;

0
source

Source: https://habr.com/ru/post/900470/


All Articles