(1) Wayward code!
if (month = 1||3||5||7||9||11){
is not right at all!
Firstly, = is for assignment whereas == is for comparison (this error is all over your code!)
And secondly, to test 'month' against multiple values you need to compare it against each number in turn (with ==) and then || the results of all the comparisons (this error is also repeated.)
if ((month == 1) || (month == 3) || // etc
(you don't need the extra brackets here, but I find it makes it easier to read.)
This (fixing the comparison operator)
if (month == 1||3||5||7||9||11){
is or-ing the result of the comparison
month == 1
with the
values 3, 5, ... (which are all equal to true as they are non-zero.) So this test will always evaluate to true, whatever the value of 'month'. It pretty much looks like this to the compiler:
if ((month == 1) || true || true || true || true || true){
(The original code is setting month to the value 1 (which is true) and then or-ing that with true; so the if statement will always evaluate to true.)
And this line is even worse (why
,
this time rather than
||
??)
else if (month = 4,6,8,10,12){
See "Comma operator" section on this page.
http://www.cplusplus.com/doc/tutorial/operators/
(This will also always evaluate to true.)
(2) Misplaced code?
I think you're testing for leap years at the wrong place, which ends up with you duplicating code. (How many months are affected by leaping?)
(3) Incomplete code.
Testing for leap years is a little bit trickier than checking if the year is divisible by four.
* Leap Years are any year that can be evenly divided by 4 (such as 2012, 2016, etc)
* except if it can can be evenly divided by 100, then it isn't (such as 2100, 2200, etc)
* except if it can be evenly divided by 400, then it is (such as 2000, 2400) |
https://www.mathsisfun.com/leap-years.html
(4) Extra code?
You could also use && here? (Instead of nested if statements.)
1 2 3 4 5
|
if (date >=1){
if (date <=31){
cout << "The date is valid";
}
}
| |
Have you used arrays yet? If so, think how you could use one to squash your implementation down further.
Andy
PS The indenting in your code is a bit off, which makes it that bit harder to read.