← C++ from Scratch Lesson 48 of 62 · 10 XP

Debugging

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

Debugging is looking for where the program behaves differently from what you think.

  1. Reproduce the error on a small example.
  2. Narrow down the place: debug output std::cerr << "i=" << i << " sum=" << sum << '\n'; — std::cerr goes to a separate error stream and doesn't get in the way of the real output.
  3. Check your assumptions: assert(n > 0); from <cassert> stops the program if the condition is false, and tells you where.
  4. On your own computer there's a debugger (gdb, lldb, the debugger in an IDE): breakpoints, step-by-step execution, viewing variables. -g at compile time adds debugging information, and -fsanitize=address,undefined catches going out of bounds and UB right at the moment of the error.

Usual suspects: loop bounds (< or <=), uninitialised variables, integer division, = instead of ==, a forgotten break in a switch.

Task. The program has three errors. It should read n and n numbers and print the average with two decimal places and the count of numbers greater than the average. Find and fix the errors (you can use debug std::cerr).

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.