Question
Save, compile, and run (F11) the C++ program. Note the incorrect result of 0. Observe the data types of the constants/variables used in the calculation,
Save, compile, and run (F11) the C++ program. Note the incorrect result of 0. Observe the data types of the constants/variables used in the calculation, and recall that int/int = int. We have a logic error!
Change the data type of batAvg to double, recompile, and run the program again. Did that fix the problem? No? Recall that the expression on the right side is evaluated first, and then assigned to the variable on the left side. Since the expression is still int/int, the result is 0 (int), which is then promoted to 0.0 (double) when it is assigned (=) to batAvg.
Use casting in the assignment statement to resolve the error (do NOT change the data types of the constants!). Save, compile, and run (F11) the program. The correct result should be 0.292162
#include using namespace std; //declare constants const int AT_BAT = 421; const int HITS = 123; int main() { //declare variables int batAvg; //calculate results batAvg = HITS / AT_BAT; //display results cout << "The batting average is " << batAvg << endl; return 0; } //end main()
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started