Edmund Rojas
Edmund Rojas

Reputation: 6606

C++ strange output when adding integers or doubles together

Im having a problem with adding numeric types together in c++ and cant figure out why its happening, I expect when I input 3 bowling scores together I will get 9 or 9.00, instead I get something crazy like 3.31748e+258, what am I doing wrong? any help will go a long way thanks!

#include<iostream>
#include<cmath>
#include <iomanip>
#include <cstdio>   
#include <cstdlib>

using namespace std;

int main()
{
/*Coordinate variables*/
double bowlTotal;
double bowlScore;  
const int FIVE_PLAYERS = 5;

for( int players = 0; players < FIVE_PLAYERS ; players++ )
{
    cout << "Player " << players + 1 << endl << endl;

    for( int games = 0; games < 3; games++ )
    {

     double score;
     score = 0;

     cout << "Please enter score for game #" << games + 1<< ": ";
     cin >> score;
     cout << endl;

     bowlTotal += score;
    } 


     cout << endl << endl <<"The final score for player #"<< players + 1 << " = " << bowlTotal << endl << endl;
     bowlScore += bowlTotal;
}
cout << endl << endl <<"The final team score = " << bowlScore << endl << endl;

system("PAUSE");
return 0;
}

Upvotes: 0

Views: 1957

Answers (2)

Karthik T
Karthik T

Reputation: 31952

You need to initialize your variables to 0 before you use them, as shown below.

double bowlTotal = 0.0;
double bowlScore = 0.0;  

Typically compiler will not do this for you, and the variables will be filled with effectively garbage values, to which you add your scores.

As GManNickG succinctly puts it, reading an uninitialized variable is undefined behavior.

Upvotes: 7

OldProgrammer
OldProgrammer

Reputation: 12159

You did not initialize bowlTotal or bowlScore, so they contain garbage.

Upvotes: 2

Related Questions