hi, im learning c++ and this is part of a project i'm doing. i cannot figure out why only the last part of this if else statement is doing anything. no matter what I enter as the sex, it only ever says the sex is R.
I have tried flipping it the other way around but then it only ever displays T as the sex.
i don't know what i've done wrong, thanks for help. this is the part i can't figure out
1 2 3 4 5 6 7 8 9 10 11
if (sex = 3) //this decides what sex factor to use
{sexDisplay = "T";
sexfac = 0.53;}
elseif(sex = 2)
{sexDisplay = "S";
sexfac = 0.25;}
else (sex = 1);
{sexDisplay = "R";
sexfac = 0.77;}
= in if should trigger a warning.
if (x = 3) //assign x the value 3. is x zero? If not, proceed as 'true'.
if(x==3) //is x 3? If so, proceed. this is what you usually want.
you have == in your other ones ...
anti-addbot:
hi, im learning c++ and this is part of a project i'm doing. i cannot figure out why only the last part of this if else statement is doing anything. no matter what I enter as the sex, it only ever says the sex is R.
I have tried flipping it the other way around but then it only ever displays T as the sex.
i don't know what i've done wrong, thanks for help
if (sex = 3) //this decides what sex factor to use
{sexDisplay = "T";
sexfac = 0.53;}
you also have missing an if and a bad ; on the last else.
if (whatever); //conditionally executes the ; which does nothing!
statement; //this ALWAYS EXECUTES
and human readables are not c++ accepted:
if(x && y == 3) //if x is not zero and y is 3, not 'if x and y are both 3')
if(whatever)
statement
else if(another)
statement2
else (condition without if that is ignored)
{
//stuff that always happens
}
you will get used to it. {} and () may or may not actually DO anything beyond marking code for readability. (sex = 1); is the same as sex = 1; and actually makes it harder to read.
{sexDisplay = "R";
sexfac = 0.77;} //the {} pair do nothing here, and mislead the reader as well, because there is no 'outer statement' for the 'block of code' inside the {} pair.
it is OK to occasionally use {} to set off a block of code, to scope a variable or make it easier to read, but this is unusual (for readability) and serves a purpose for scoping (still, do not do this excessively). Here, its just a mistake though.
good! Make sure you understand this, it is IMPORTANT.
c++ compiler ALLOWS you do make these mistakes (with a warning) because they are legit code structures. So you need to understand the proper format for conditional blocks to avoid these mistakes again, as they will compile but fail to work properly if you do not do it right.