Noob at C++ Need help with class

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.

Thank you

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
//This program calculates batting average of a baseball player

#include <iostream>
#include <cmath>
using namespace 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;
}
Last edited on
Update...

I ran the code on another computer and bumped into the same problem, is that enough to indicate the issue is the code?
Add this after line 19: cin >> atBat ;

On line 22, verify that atBat is not zero.
1
2
3
4
5
if( atBat != 0 )
{
     battingAverage = hits / atBat ;
     cout << "The player's batting average is " << battingAverage << '\n' ;
}
JLBorges thank you!! wow super noob error, can't believe I was missing that lol
Last edited on
Should hits and atBat be declared int or double?

When I declare them as int, result is zero, but when I declare them as double, I get 0.6.
Declare then as integers (they are whole numbers).
When performing the calculation of average, avoid integer division.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#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
            const double 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" ;
}
Topic archived. No new replies allowed.