11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 10: Debugging C++ 145Notice the addition of the output statements to display nSum, nNums, andnValue on each iteration through the loop.The result of executing the program with the now standard 1, 2, 3, and –1input is shown next. Even on the first loop, the value of nSum is unreasonable.In fact, at this point during the first loop, the program has yet to add a newvalue to nSum. You would think that the value of nSum should be 0.This program generates incorrect resultsEnter another number:1nSum = 4370436nNums= 0nValue= 1Enter another number:2nSum = 4370437nNums= 1nValue= 2Enter another number:3nSum = 4370439nNums= 2nValue= 3Enter another number:-1Average is: 1456814Press any key to continue . . .On careful examination of the program, nSum is declared, but it isn’t initializedto anything. The solution is to change the declaration of nSum to thefollowing:int nSum = 0;Note: Until a variable has been initialized, the value of that variable isindeterminate.When you have convinced yourself that you have found the problem, “cleanup” the program as follows (this version is ErrorProgram3.cpp on theenclosed CD-ROM):// ErrorProgram - this program averages a series// of numbers#include #include #include

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!