11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 10: Debugging C++ 143This addition generates the following output:This program is designed to crash!nNums = 0Enter another number:1nNums = 0Enter another number:2nNums = 0Enter another number:3nNums = 0Enter another number:You can see where nNums is initialized to 0, but where is it incremented? Itisn’t, and this is the bug. Clearly nNums should have been incremented duringeach loop of the input section. I edit the while loop into a for loop as follows:for (int nNums = 0; ;nNums++)Catching bug #2Having fixed a bug, execute the program using the same 1, 2, 3, and –1 inputthat crashed the program earlier. This time, the program doesn’t crash, but itdoesn’t work either. The output shown here includes a ridiculous value foraverage:This program generates incorrect resultsEnter another number:1Enter another number:2Enter another number:3Enter another number:-1Average is: 1456814Press any key to continue...Apparently, either nSum or nNums (or both) isn’t being calculated properly. Toget any farther, you need to know the value of these variables. In fact, itwould help to know the value of nValue as well because nValue is used tocalculate nSum.Now you modify the for loop as follows to learn the values of the nSum,nNums, and nValue (this version of the program appears on the CD-ROM asErrorProgram2.cpp):

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

Saved successfully!

Ooh no, something went wrong!