if (age > 40 && age < 60)
or
if (age > 40 & age < 60)
As you can see I am not sure if C++ uses two and signs or one.
The first one is the correct Logical AND if (age > 40 && age < 60)
&& is a Logical AND operator
& - could be a Reference ("address of") operator or a Bitwise AND operator (which is the case in your second example) depending on where it appears in expression. Also, see Operators in C and C++.
Use this for the correct results:
if ((age > 40) && (age < 60))
It's &&, single ampersand is a bitwise and function. In a lot of cases it may work out the same if you are using ints, but there will be other data types that cause problems.
Related
I had the task of finding a logical expression that would result in 1 if and only if a given number n is a multiple of 2019 and is NOT from the interval (a, b).
The textbook gave the following answer and I don't really understand it:
a>=n || b<=n && (n%3==0 && n%673==0)
The thing between those parantheses I understand to be equivalent to n%2019==0, so that's alright. But I don't understand why this works, I mean the && operator has higher priority that the || operator, so wouldn't we evaluate
b<=n && (n%3==0 && n%673==0)
first and only at the end if n<=a? I thought that if I were to do it, I would do it like this:
(a>=n || b<=n) && (n%3==0 && n%673==0)
So I just added that extra set of parantheses. Now we would check if the number is not in the interval (a, b), then we would check if it is a multiple of 2019 and then we would 'and' those to answers to get the final answer. This makes sense to me. But I don't understand why they omitted that set of parantheses, why would that still work? Shouldn't we consider that && has higher priority than ||, so we add an extra set of parantheses? Would it still work? Or is it me that is wrong?
Trying it out shows that the expression as written without the extra parentheses doesn't work:
bool expr(int n, int a, int b)
{
return a>=n || b<=n && (n%3==0 && n%673==0);
}
expr(1000, 2000, 2018) for example evaluates to true, even though it is not a multiple of 2019.
As you pointed out, the logical AND operator && has higher precedence than the logical OR operator || (reference), so the expression is equivalent to:
a>=n || (b<=n && (n%3==0 && n%673==0))
which is always true when n <= a, even if it's not a multiple of 2019.
A clearer expression would be:
(n % 2019 == 0) && (n <= a || n >= b)
I'm teaching myself C++ and was writing some code to calculate grade averages with arrays. Everything works except for when I try to display the results. I get the error "expected primary-expression before '<' token" on this line of code.
if(grade1 >= 0 && < 60)
followed by a single cout statement and a semi-colon. I looked in the book I am using and on c++ forums. My book looks just like my example and online everyone was missing a semi-colon or something else. Is that my case too?
Thanks!
You need to include 'grade1' on both comparisons.
if (grade1 >= 0 && grade1 < 60)
What you want is this:
if(grade1 >= 0 && grade1 < 60)
You need to provide a variable for each condition in your if statement. The grade1 variable will not carry over for other comparisons.
You must write like this
if (grade1 >= 60 && grade1 < 60){ //code here }
1.Imagine condition if (obj.is_x() || obj.is_y() || obj.is_z())
Will obj.is_y() and obj.is_z() be called and evaluated if obj.is_x() returned true ?
2.Is this a bad idea(in general)? Does this code look bad ?
bool isbn13_prefix_valid (const string& prefix)
{
unsigned num = stoi(prefix);
if (num == 978 || num == 979) return 1; //super common ones
else if ( num >= 0 && num <= 5 || num == 7 || num >= 600 && num <= 649
|| num >= 80 && num <= 94 || num >= 950 && num <= 989
|| num >= 9900 && num <= 9989 || num >= 99900 && num <= 99999)
return 1;
return 0;
}
No, it will not, due to short-circuiting.
Yes, that code looks bad. Not because it's incorrect, but because you're stuffing an extremely long conditional into a single if statement. Try refactoring your code to make it cleaner.
Your code is absolutely fine. I'd like to see a comment where these strange numbers come from, that's all.
Turning it into a dozen trivial functions as has been suggested is in no way helpful. It actually makes it a lot harder to read the code, because it gets spread out over many many lines of code. Yes, it is complex. But that's due to the problem being complex, and trying to spread the complexity out doesn't help one bit.
Your actual question: In a || b, a is evaluated first. If it is true, then b is not evaluated and the result is true. If a is false, then b is also evaluated and the result is true or false, depending on the result of b.
An optimising compiler may start evaluating b before it has finished evaluating a, if it can prove that the evaluation of b has no side effects, and if it believes that (mostly due to parallelism in the hardware) it is on average faster to evaluate as much in parallel as possible, even if some things are evaluated when it wasn't necessary. But this is not noticable in the results of your code, and will only make the code faster.
bool operator < (Time obj_a, Time obj_b)
{
return ((obj_a.hours<=obj_b.hours || obj_a.minutes<=obj_b.minutes) &&
(obj_a.hours<=obj_b.hours || obj_a.minutes<=obj_b.minutes));
}
bool operator > (Time obj_a, Time obj_b)
{
return (obj_a.hours>=obj_b.hours || obj_a.minutes>=obj_b.minutes);
}
bool operator == (Time obj_a, Time obj_b)
{
return (obj_a.hours==obj_b.hours && obj_a.minutes==obj_b.minutes);
}
Can somebody tell me whats wrong with these operators.They are comparing time of hours and minutes.but i am not getting correct comparison.I have defined a class of Time in which hours and minutes are stored.
There's a lot wrong with this code. First off, you're reducing < comparisons to <= comparisons, which (if the rest of your logic were correct) would mean that equal times would compare either < or >, depending on the order of arguments to the comparison routines.
Then,
((obj_a.hours<=obj_b.hours || obj_a.minutes<=obj_b.minutes) &&
(obj_a.hours<=obj_b.hours || obj_a.minutes<=obj_b.minutes))
performs exactly the same comparison twice in an &&, so it's actually doing just
obj_a.hours<=obj_b.hours || obj_a.minutes<=obj_b.minutes
This doesn't work because it wants either the hours, or the minutes to be <=. That means 11:30 <= 10:40 because 30 <= 40.
The easiest way to tackle this problem is to reduce your comparisons on time objects to comparisons on minutes only, e.g.
a.hours * 60 + a.minutes < b.hours * 60 + b.minutes
I recently encountered with this question: How to reduce this expression: s>73?61:60;.
The hint given was that Instead of using conditional operator we could use a simple comparison which will work fine.
I am not sure but I think it is possible with some GCC extension,although I am unable to figure it out myself.
EDIT:The whole expression is this : s-=s>73?61:60
Just like the other answers:
s -= (s > 73) + 60;
This expression works because the spec defines the results of the relational operators. Section 6.5.8 paragraph 6:
Each of the operators < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to) shall yield 1 if the specified relation is true and 0 if it is false. The result has type int.
How to reduce this expression: s-=s>73?61:60;
How about:
typedef int Price;
Price getPriceAfterRebate(const Price priceBeforeRebate)
{
const Price normalRebate = 60;
const Price superRebate = 61;
const Price superRebateThreshold = 73;
Price returnValue = priceBeforeRebate;
if (priceBeforeRebate > superRebateThreshold)
{
returnValue -= superRebate;
}
else
{
returnValue -= normalRebate;
}
return returnValue;
}
Tada! An ugly piece of unmaintainable code is reduced to a readable and maintainable block of code.
This is such an ugly piece of code that I can't beleive I wrote it, but I think it fulfills the requirement:
My answer to the original question which was s>5?6:9:
9 - (((int)(s > 5)) * 3)
Rewritten for the updated question:
61 - (int)(s > 73)
Maybe this?
60 + !!(s > 73)
The double-bang maps non-zero values to 1 and zero to zero.
What is the value of (s>5)? Could you do some arithmetic with that?
Without the hint, I would say this was a bad "gotcha" interview question that requires a particular a-ha insight that's not correlated with ability. With the hint, it's... nice, but dim.
If we assume that True = 1 and False = 0, then doesn't this work:
s-= (60 + (s > 73))
It can be thought of as s -= (s > 73) + 60 as > is a relational operator and it will return 1 or 0 depending on result of expression s > 73 ,As the return value is int so it will work fine