Hello all,
I'm taking a C++ class in college and I'm really starting to dig it. I am, however, very new and inexperience with C++ and programming in general.
I'm trying to complete a really simple batting average program from our book in class, but DEV C++ crashes every time I input the first requested data.
Please can someone look at my code and tell me if something in it could be causing this issue or if I should look at something to find a solution.
//This program calculates batting average of a baseball player
#include <iostream>
#include <cmath>
usingnamespace std;
int main()
{
//Declaration
int hits, atBat ;
float battingAverage;
//Get the number of hits
cout << "Enter the player's number of hits: ";
cin >> hits;
//Get the number of times at bat.
cout << "Enter the player's number of times at bat: ";
//Calculate the batting average
battingAverage = hits / atBat ;
//Display the batting average
cout << "The player's batting average is " << battingAverage;
return 0;
}
#include <iostream>
int main()
{
//Get the number of hits
int hits ;
std::cout << "Enter the player's number of hits: ";
std::cin >> hits;
//Get the number of times at bat.
int atBat ;
std::cout << "Enter the player's number of times at bat: ";
std::cin >> atBat ;
if( hits >= 0 ) // must be non-negative
{
if( atBat > 0 ) // must be positive
{
//Calculate the batting average
constdouble battingAverage = double(hits) / atBat ; // avoid integer division
//Display the batting average
std::cout << "The player's batting average is " << battingAverage << '\n' ;
}
else std::cerr << "number of hits can't be negative\n" ;
}
else std::cerr << "number of times at bat is non-positive\n" ;
}