Procedural Programming with C++
Don't do this
3 expression mistakes that cost C++ marks
3 mistakes that cost marks in C++ expressions. Say the fix first.
Quick check · tap an answer to continue
Lesson notes
Evaluate expressions using precedence, integer division, modulus and implicit/explicit casts
Key points
- Thinking 7/2 is 3.5: Two ints use integer division, so 7/2 gives 3; write 7.0/2 to get 3.5.
- Casting after dividing: static_cast<double>(sum/count) casts too late; cast first: static_cast<double>(sum)/count for your GPA.
- Ignoring precedence: Multiplication, division and modulus bind before addition, so 2+10%4*3 is 2+6, which is 8.
Takeaway: Cast an operand to double before dividing, not the result.
Quick check: With int sum = 15 and int count = 4, what does sum/count evaluate to?
- 3.75
- 3
- 4
Both operands are int, so integer division drops the fraction, giving 3.
operator precedenceinteger divisionstatic_cast
Lessons like this, for your syllabus.
Short narrated study videos written for your course, level and exam. Free to start.
Get lessons for your own syllabus