I need help with a program for school. We had to write a program that asks the user for information about a baseball player. We need to calculate the players batting average with their games played, number of times at bat and number of hits. I am running into an issue where my computation for the average is outputting a set number and not performing any computations. I am entering whole integers for all the variables that are used for calculation. So i would input numbers like 1, 4 , 10 etc... As the program stands the value my formula is setting itself equal to is 15903.876. All of my variables used for the average formula are declared as integers and the batting average itself is declared as a double. I have done some debugging my self and found that the computation messes up when it divides the number of times at bat by the number of hits. If anyone could help me figure out the issue i would appreciate it.
//libaries
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;
class battingAverage
{
public:
string pName;
int nBats;
int tHits;
int gPlayed;
int gcalled;
double average;
double average1;
double playeraverage;
};
int main()
{
string numberPlayers;
int nplayers;
//enters the number of players the user wants to enter data for
cout << "Enter the number of players you want to enter data for: ";
cin >> numberPlayers;
cout << endl;
//converts the value of numberPlayers to nplayers
istringstream convert(numberPlayers);
//sets integer nplayers equal to the value of the string numberPlayers
if(! (istringstream(numberPlayers) >> nplayers) )
{
nplayers = 0;
}
cout << "This program calculates the batting average of baseball players.\nYou may enter data for " << nplayers << " players." << endl;
battingAverage ba[nplayers];
int index = 0;
//while statement to get data
while(index < nplayers)
{
cout << "Enter the players last name: " << endl;
cin >> ba[index].pName;
cout << "Enter the number of games the player played: " << endl;
cin >> ba[index].gPlayed;
cout << ba[index].gPlayed << endl;
cout << "Enter the number of games the player was called in for: " << endl;
cin >> ba[index].gcalled;
cout << ba[index].gcalled << endl;
cout << "Enter the number of times the player was at bat: " << endl;
cin >> ba[index].nBats;
cout << ba[index].nBats << endl;
cout << "Enter the number of time the player hit: " << endl;
cin >> ba[index].tHits;
cout << ba[index].tHits << endl;
if(ba[index].tHits > ba[index].nBats)
{
cout << "Enter a valid value for the number of times the player hit: ";
cin >> ba[index].tHits;
}
cout << endl;
index++;
}
//rounds average to 3 decimal places
cout << fixed << setprecision( 3 );
//average formula
ba[index].playeraverage = (ba[index].nBats / ba[index].tHits) * (ba[index].gPlayed / ba[index].gcalled);//error
cout << ba[index].playeraverage << endl << endl;//just temp line to check calculation of average.
ba[index].average = .000;
ba[index].average1 = .099;
while(ba[index].average < 1 && ba[index].average1 < .899)
{
ba[index].average +=.100;
ba[index].average1 += .1;
//prints chart
cout << setprecision( 1 ) << ba[index].average << "00" << setprecision( 3 ) << setw(12) << ba[index].average1 << endl;
}
cout << "1.000" << setw(12) << "1.000" << endl;
//version of system pause
cout << "\nPress enter to continue...";
cin.sync();
cin.ignore();
return 0;
}
On this line:
ba[index].playeraverage = (ba[index].nBats / ba[index].tHits) * (ba[index].gPlayed / ba[index].gcalled);//error
You have this expression:
(ba[index].nBats / ba[index].tHits)
Because both nBats and tHits are integers, you're using only integer math.
The answer will be an integer.
For example:
nBats = 10 & tHits = 3, you'd expect the expression to be 3.333.
But it would only be 3
To fix this, I recommend changing to:
((double)ba[index].nBats / ba[index].tHits)
Same thing again with the expression about gPlayed and gcalled.
Your value of index is wrong during the calculations.
I found this as soon as I put your code in a debugger and stepped through it, something you really should have done yourself.
You start with int index = 0;, and increment it as the user puts in each player's data.
At the end of the input-loop, index is now the same as the number of players.
(eg. if you had 5 players, index is now 5, and the player data is stored in ba[0], ba[1], ba[2], ba[3], and ba[4])
Note that at this point ba[5] is NOT valid data. But that is exactly where ba[index] is!
You do all your calculations on ba[index], which is invalid data, and you wonder why you get meaningless results?
I recommend you set index back to 0 before starting your calculations, and make another loop that does the necessary calculations for each player 0...4.
Related
I was trying to make a table that shows the different rates of the population of pigeons over a certain amount of time. So far, it only gives the max and min population over the interval rather than a table. For example for the input you could put 1.5 for the initial and 2.0 for the final. When the code runs, it only gives the amount of pigeons over that time, and the highest and lowest population(Or it's supposed to). I am trying to get a full table to represent the rate of change in the population. Any help?
#include<iostream> //Required for cout prog 4_5!
#include<cfloat> //required for DBL_MAX
#include<cmath>
#include<iomanip>
using namespace std;
int main()
{
double maxRate, minRate(DBL_MAX),PercentRate,klast,kfirst,kinc,k(-1.6); //Declare and initialize objects
cout << "Hello User! This program will be calculating the different rates of the pigeon population in New York City.";
cout << "You will now be prompted to enter the needed values of time for the program to calculate. Using the range of 0 to 3, please enter the Initial Time of years in a decimal.";
cin >> kfirst;
cout << "Next, the final time";
cin >> klast;
cout << "And finally, enter the increment of time 0.1";
cin >> kinc;
int loops;
cout << " minRate maxRate PercentRate ";
cout<< scientific <<setprecision(3);
for (int i = 1; i<=loops ; ++i);
loops=int(klast-kfirst)/kinc+1;
{
PercentRate=2*sin(kinc)*(k*pow(kinc,3)-5.2*pow(kinc,2)+27*kinc-4.1);
if (PercentRate < minRate)
{
minRate = PercentRate;
}
if (PercentRate > maxRate)
{
maxRate=PercentRate;
}
k=k+kinc;
cout << setw(10) << maxRate << setw(10) << minRate << setw(10) << PercentRate << endl;
}
//Output of rate change of pigeons
cout << "The minimum rate of pigeons in New York City is " << minRate;
cout << "The maximum rate of pigeons in New York City is " << maxRate;
return 0;
}
I have a assignment I've been working on and my code is working but the results are off by a hair. I know the issue has to do with rounding but I just can't seem to figure out where the issue lies. I've included the assignment details as well as the results i'm getting versus the expected result. Any help is appreciated.
Link for images https://imgur.com/a/bqIcxfT
'''
// This program will display the size of a population for given number of years
// taking into account annual birth and death rates as well as the number of
// people who move away and move into the area.
#include <iostream>
#include <iomanip>
using namespace std;
//Function prototype
double calculatePop (double, double, double, int, int);
int main ()
{
double P; // Starting population
double B; // Annual birth rate
double D; // Annual death rate
int A; // Average number of people who arrive
int M; // Average number of people who move away
int nYears; // The number of years to display
cout << "This program calculates population change." << endl;
// Set numeric formatting
cout << setprecision(0) << fixed;
// Get starting population size
cout << "Enter the starting population size: ";
cin >> P;
while (P<2){
cout << "Starting population must be 2 or more.";
cout << "Please re-enter:";
cin >> P;}
// Get the annual birth rate
cout << "Enter the annual birth rate (as % of current population): ";
cin >> B;
while (B<0){
cout << "Birth rate percent cannot be negative.";
cout << "Please re-enter:";
cin >> B;}
B/=100;
// Get annual death rate
cout << "Enter the annual death rate (as % of current population): ";
cin >> D;
while (D<0){
cout << "Death rate percent cannot be negative.";
cout << "Please re-enter:";
cin >> D;}
D/=100;
// Get number of people who arrive
cout << "How many individuals move into the area each year? ";
cin >> A;
while (A<0){
cout << "Arrivals cannot be negative.";
cout << "Please re-enter:";
cin >> A;}
// Get number of people who move away
cout << "How many individuals leave the area each year? ";
cin >> M;
while (M<0){
cout << "Departures cannot be negative.";
cout << "Please re-enter:";
cin >> M;}
// Get number of years to see data for
cout << "For how many years do you wish to view population changes? " << endl << endl;
cin >> nYears;
while (nYears<1){
cout << "Years must be one or more.";
cout << "Please re-enter:";
cin >> nYears;}
cout << "Starting population: " << P << endl << endl;
//Display the population to user
for (int y=1; y<=nYears; y++)
{
P = calculatePop(P, B, D, A, M);
cout << "Population at the end of year " << y << " is " << P << ".\n";
}
}
double calculatePop (double P, double B, double D, int A, int M)
{
double N; //New Population Size
N = P + (B*P) - (D*P) + A - M;
return N;
}
'''
The value is correctly calculated but not outputted the same way as in the assignment. Setting setprecision(0) along with fixed will round the number to the nearest integer while the result shown in the assignment is the truncated number. To truncate the result, use
cout << "Population at the end of year " << y << " is " << int(P) << ".\n";
just started reading a C++ book and one of the practice problems was to write a small calculator that takes as input one of the four arithmetic operations, the two arguments to those operations, and then prints out the results.
Sadly, the program works up until the user inputs the arithmetic option.
So if I chose to do multiplication, id write "Multiplication" and it was just stay there and not do anything after.
Image of the problem im having
#include <iostream>
#include <string>
using namespace std;
int main(){
// Simple calculator program
// Declaring three variables
float numberOne;
float numberTwo;
string operationOption;
// Asking the user which two numbers he/she will use
cout << "Enter the first number you would like to apply a arithmetic operation to: ";
cin >> numberOne;
cin.ignore();
cout << "Now enter the second number: ";
cin >> numberTwo;
cin.ignore();
// Using cin to input users selection
cout << "Enter the operation you want to perform." << endl;
cout << "The options you have are: " << endl;
cout << "Multiplication, Subraction, Division and Addition: " << endl;
cin >> operationOption;
cin.ignore();
cin.get();
// Where it all happens
if ( operationOption == "Multiplication" ) {
cout << "The first number multiplied by the second number is: " << numberOne * numberTwo << endl;
} else if ( operationOption == "Division" ) {
cout << "The first number divided by the second number is: " << numberOne / numberTwo << endl;
} else if ( operationOption == "Subtraction" ) {
cout << "The first number subtracted by the second number is: " << numberOne - numberTwo << endl;
} else if ( operationOption == "Addition ") {
cout << "The first number added to the second number is: " << numberOne + numberTwo << endl;
} else {
cout << "You entered an invalid option.";
};
}
Remove line :
cin.get();
will solve your problem
I had to write a program to calculate average speed of a car during a trip and I have to prompt the user for the names of the two cities that they were traveling between. That program worked, but the next program we had to write is an addition to the last one, in which the user is prompted for how many times the program should run. I declared a new variable for the number of times the users needs the program to run. However when the program enters the loop it skips the first getline() method (asking for the origin city) and skips directly to the second getline() (method asking for the destination city). I have tried clearing the buffer and declaring the loop differently, but whatever I do the string is still read into the program as an empty string. Just wondering if I made a mistake on something or if I cannot use getline() in this instance.
Using C++ and Codeblocks IDE with the GNU Compiler (I've tried other compilers too)
Anyhow here is the code.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
//Declare Variables
string orgcity = "";
string destcity = "";
int hours = 0;
double minutes = 0.0;
int hoursmin = 0;
int minutesmin = 0;
int minutesmax = 60;
double dist = 0.0;
double totalhours = 0.0;
double avespeed = 0.0;
double num1 = 0;
cout << "How many times would you like to calculate the average speed: ";
cin >> num1;
for(num1; num1 > 0; --num1)
{
//Collect Data
cout << "Enter the city of origin: ";
getline(cin, orgcity);
cout << "Enter the destination city: ";
getline(cin, destcity);
//If Statements and Loops...Start here
do {
cout << "Enter the number of hours spent in travel: ";
cin >> hours;
if (hours < hoursmin)
cout << " Invalid number of hours - must be >= 0" << endl;
} while (hours < hoursmin);
do {
cout << "Enter the number of minutes spent in travel: ";
cin >> minutes;
if (minutes >= minutesmax){
cout <<" Invalid number of minutes - must be in range 0..59" << endl;
}
if (minutes <= minutesmin) {
cout << " Invalid number of minutes - must be in range 0..59" << endl;
}
} while (minutes >= minutesmax);
//End Here
cout << "Enter the distance (in miles) between the two cities: ";
cin >> dist;
cout << endl;
//Formula and Final Prompt
totalhours = (hours + (minutes / 60.0));
avespeed = dist / totalhours;
cout << "The average speed of the vehicle traveling" << endl;
cout << "between " << orgcity << " and " << destcity << " is " << fixed << setprecision(2) << avespeed << " miles per hour." << endl;
cout << "-------------------------------------------------------------------------------" << endl;
}
return 0;
}
When you read the number of times the loop should be run, the input operator reads the number, but leaves the newline in the buffer. This means that the first call to getline reads that single newline and nothing more.
To make sure you skip anything after that number, up to and including the newline, you can use e.g.
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
I've been trying to create a simple program that allows me to display a total score after the user has entered the ammount of successful hits, totalHits, by multiplying that input with the constant variable POINTS resulting in another variable; score.
I didn't think creating such a program would be any problem, but as usual, I was wrong.. When I run the program score is always random, even if I enter '1' as totalHits every time. It can differ from 444949349 to -11189181 to name a couple of examples. I have no idea what I've done wrong, so it would be great if someone could give me a clue as to what to do next :)
Here's the code:
#include <iostream>
using namespace std;
int main()
{
const int POINTS = 50;
int totalHits;
int score = totalHits * POINTS;
cout << "Please enter the ammount of successful hits: ";
cin >> totalHits;
cout << "You hit " << totalHits << " targets, and your ";
cout << "score is " << score << " ." << endl;
cin.ignore(cin.rdbuf()->in_avail() + 2);
return 0;
}
Big thanks to KerrekSB and Paddyd for providing me with the correct answer. Here's the finished code with comments:
#include <iostream>
using namespace std;
int main()
{
const int POINTS = 50;
int totalHits;
cout << "Please enter the ammount of successful hits: ";
cin >> totalHits;
cout << "You hit " << totalHits << " targets, and your ";
/*As you can see I moved the line below from the top of the code.
The problem was I had not properly learned how C++ executes the code.
The orignal code was written in a way that calculates `score` before
the user could decide it's value, resulting in a different total score than
it should have been. In the finished code, the user inputs what
value `totalHits` is, THEN score is calculated by using that value. */
int score = totalHits * POINTS;
cout << "score is " << score << " ." << endl;
cin.ignore(cin.rdbuf()->in_avail() + 2);
return 0;
}
int totalHits;
int score = totalHits * POINTS;
You are multiplying by an uninitialized variable (totalHits)! You need to apply a value to totalHits before doing this calculation.
Try using the code like this:
const int POINTS = 50;
int totalHits;
int score;
cout << "Please enter the ammount of successful hits: ";
cin >> totalHits;
cout << "You hit " << totalHits << " targets, and your ";
score = totalHits * POINTS; //totalHits has a value here
cout << "score is " << score << " ." << endl;
cin.ignore(cin.rdbuf()->in_avail() + 2);
return 0;