Reputation: 4180
I am new to c++ and I am trying to increase cars starting with value 50, but only increase by one if the youdamage is greaters than cardamage. I want cars to hold its value for the next time it does through the loop. I 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
{
Upvotes: 8
Views: 28356
Reputation: 4090
By doing this:
int car = car + 1;
You are re-defining car as an integer.
see:
#include <stdio.h>
int car;
int main() {
car = 0;
for (int i = 0; i < 10; i++) {
int car = 0;
car++;
}
printf("%3d", car);
}
vs
#include <stdio.h>
int car;
int main() {
car = 0;
for (int i = 0; i < 10; i++) {
car++;
}
printf("%3d", car);
}
Upvotes: 1
Reputation: 39294
I don't see a loop, but I'm going to hazard a guess that your problem is that you're doing this line:
int car = car + 1;
in your:
if(carDamage < yourDamage)
statement which means that you're redeclaring each time, resetting its value.
write the int car;
outsize the statement and just do ++car;
inside the loop where you originally wrote int car = car + 1;
Upvotes: 0
Reputation: 2645
Your problem is that when you say
int car = car + 1;
You are basically creating a local variable called car (local to the if statement) which is assigned the value of 51 (since the original local scope variable (local to main) contains 50 and you add 1). This local variable (the on in the if statement) is destroyed once you get out of the if statement.
If you change this to
car = car + 1;
You are now modifying the variable local to main, and thus the update will be kept.
Upvotes: 0
Reputation: 2487
You are declaring a new variable car
inside the if statement which hides the original car
variable from the above scope. Removing the type will allow you to reference the existing variable instead of declaring a new one.
In short, change
int car = car + 1;
to
car = car + 1;
Upvotes: 0
Reputation: 20272
You're declaring a new variable shadowing the original one.
change
int car = car + 1;
to
car = car + 1;
Upvotes: 10
Reputation: 838226
You need to reassign to the same variable. You are declaring a new variable.
Change this:
int car = car + 1;
To this:
++car;
Upvotes: 9