I am trying to make a program that calculates the baseball player averages , and keeps asking until it reaches the user set amount of players. I have to then output the data into a graph that has the players batting average with a * marking where it falls into.
This is what I have so far:
#include <iostream>
#include <string>
using namespace std;
class BattingInfo
{
public:
char fname[25];
char lname[25];
float hits;
float battimes;
float games;
float tgames;
float average;
float averaget;
float gaverage;
};
bool getd(BattingInfo& bi);
void displayd(BattingInfo& bi);
int main()
{
int players;
BattingInfo bi[9999];
cout <<"Please input the number of players:\n";
cin >> players;
int index;
index = 0;
while (getd(bi[index])&& index < players - 1)
{
index++;
}
cout << "\n\nData Entries: \n";
for (int i = 0; i <= index; i++)
{
displayd(bi[i]);
}
}
bool getd(BattingInfo& bi)
{ cout <<"Please input the Players first name:\n";
cin >> bi.fname;
cout <<"Please input the Players last name:\n";
cin >> bi.lname;
cout << "Please input the number of number of successful hits of the player.\n";
cin >> bi.hits;
cout << "Please input the numer of times at bat.\n";
cin >> bi.battimes;
cout << "Please input the number of games the player participated in.\n";
cin >> bi.games;
cout <<"Please input the total numer of games the player could have batted in.\n";
cin >> bi.tgames;
system("cls");
return true;
}
void displayd(BattingInfo& bi)
{
bi.average = bi.hits/bi.battimes;
bi.gaverage = bi.games/bi.tgames;
bi.averaget = bi.average*bi.gaverage;
cout <<"Batting Average: " << bi.averaget << endl;
cout << ".000 - .099";
if (bi.averaget > .0 && bi.averaget < .1)
{ cout << "*";}
cout << "\n.100 - .199";
if (bi.averaget > .099 && bi.averaget < .2)
{ cout << "*";}
cout << "\n.200 - .299";
if (bi.averaget > .199 && bi.averaget < .3)
{ cout << "*";}
cout << "\n.300 - .399";
if (bi.averaget > .299 && bi.averaget < .4)
{ cout << "*";}
cout << "\n.400 - .499";
if (bi.averaget > .399 && bi.averaget < .5)
{ cout << "*";}
cout << "\n.500 - .599";
if (bi.averaget > .499 && bi.averaget < .6)
{ cout << "*";}
cout << "\n.600 - .699";
if (bi.averaget > .599 && bi.averaget < .7)
{ cout << "*";}
cout << "\n.700 - .799";
if (bi.averaget > .699 && bi.averaget < .8)
{ cout << "*";}
cout << "\n.800 - .899";
if (bi.averaget > .799 && bi.averaget < .9)
{ cout << "*";}
cout << "\n.000 - .999";
if (bi.averaget > .899 && bi.averaget < .1)
{ cout << "*";}
cout << "\n1";
if (bi.averaget > .999)
{ cout << "*\n";}
system("\nPAUSE");
system("cls");
}
It kind of works, but the graph is outputted for each player (with only 1 players average on it), I need it to output for the whole team on one graph. Im not sure how to do that.
Here is a very basic graph that displays values from left to right. You could use this as a base and alter it to display your data. If this isn't what you are looking for, you might want to use a proper GUI library.
Note my use of vector<> instead of arrays. Don't use arrays unless you have to. Use vector.
I'm guessing this might be a school project, so finishing this yourself would probably be best.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void display_as_graph(vector<int>& numbers)
{
char space = ' ';
for(int i = 0; i < numbers.size(); i++)
{
for(int num_spaces = 0; num_spaces < numbers[i]; num_spaces++)
{
cout << space;
}
cout << "x\n";
}
}
int main()
{
vector<int> numbers;
numbers.push_back(4);
numbers.push_back(6);
numbers.push_back(8);
numbers.push_back(3);
display_as_graph(numbers);
string wait;
cin >> wait;
return 0;
}
Related
#include <iostream>
#include <stdio.h>
#include <ctype.h>
using namespace std;
class List{
private:
int A[10];
int i;
public:
List(){
i = 0;
}
void insert(){
int v;
for(int j = 0 ; j < 10 ; j++){
cout << "\nElement you want to insert: (" << i+1 << "). ";
cin >> v;
if(i <= 9){
A[i] = v;
i++;
}
else{
cout << "\nWrong Input" << endl;
break;
}
}
if(i > 9){
cout << "\nYour List Capacity is Full.\n" << endl;
}
}
void display(){
cout << "\n{ ";
for(int j = 0 ; j < i ; j++)
cout << A[j] << " ";
cout << "}\n" << endl;
}
void remove(){
int p;
cout << "\nElement you want to remove (0 - 9): ";
cin >> p;
if (i == 0){
cout << "\nList is empty!\n" << endl;
return;
}
if (p >= 0 && p < i){
for(int j = p ; j < i-1 ; j++)
A[j] = A[j + 1];
i--;
}
}
void size(){
cout << "\nYour list size is: " << i << endl;
}
void checkcapacity(){
int arrSize = sizeof(A)/sizeof(A[0]);
cout << "\nThe Capacity of the array is: " << arrSize << endl;
}
};
int main(){
List l;
int a;
cout << "\t\t\t\t\t\tWelcome to List Program!";
while(a != 4){
int choose;
cout << "\nThe Program have following options:\n1. Insert\n2. Display\n3. Remove\n4. Check Size\n5. Check Capacity\n6. Exit\n\nNote: Your list capacity is 10!";
cout << "\n\nChoose (1 - 5): ";
cin >> choose;
if (choose == 1){
l.insert();
}
else if (choose == 2){
l.display();
}
else if (choose == 3){
l.remove();
}
else if (choose == 4){
l.size();
}
else if (choose == 5){
l.checkcapacity();
}
else if (choose == 6){
a = 4;
}
}
cout << "Thank you for using this program!";
}
I'm using this class in my main function in which I call them but when the user inputs a char or string in the insert function it goes into infinte loop. Int i is my counter and it just contains the size of my array list im just trying to put a check of character that if user input a character is should show an error.
Here's one way to write your insert function
void insert()
{
int v;
for(int j = 0 ; j < 10 ; j++)
{
cout << "\nElement you want to insert: (" << i+1 << "). ";
if (cin >> v)
{
if (i < 10)
{
A[i] = v;
i++;
}
}
else
{
cin.clear(); // clear error
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // discard any pending input
}
}
if (i >= 10)
cout << "\nYour List Capacity is Full.\n" << endl;
}
The important part is the recovery from bad input. First cin.clear() is called to clear the stream error state, secondly cin.ignore(...) is called to discard any pending input.
More details here
I have this math problem which requires to find if a point lies in all the circles... I have almost all the code but it has one problem that is it checks which point lies in each circle and not if one point lies in all circles.. I think I need to do a minor change but I can't figure it out...
#include<iostream>
#include<stdlib.h>
#include<math.h>
int main()
{
using namespace std;
system("chcp 1251");
int k, m, c, ic;
float x[12], y[12], r[12], xp[12], yp[12], d;
do
{
cout << "Enter how many circles (1..12): ";
cin >> k;
}
while (k < 1 || k > 12);
for (c = 0; c < k; c++)
{
cout << "Enter coordinates of circles № " << 1 + c << endl;
cout << "x= "; cin >> x[c];
cout << "y= "; cin >> y[c];
cout << "r= "; cin >> r[c];
}
do
{
cout << "Enter how many points (1..20): ";
cin >> m;
} while (m < 1 || m > 20);
cout << "Enter coordinates of points:" << endl;
for (c = 0; c < m; c++)
{
cout << "Point № " << 1 + c << endl;
cout << "x= "; cin >> xp[c];
cout << "y= "; cin >> yp[c];
}
for (c = 0; c < k; c++)
{
cout << "Points in circle № " << 1 + c << ": ";
for (ic = 0; ic < m; ic++)
{
d = sqrtf((x[c] - xp[ic]) * (x[c] - xp[ic]) + (y[c] - yp[ic]) * (y[c] - yp[ic]));
if (d < r[c] )
cout << 1 + ic << " ";
}
cout << endl;
}
system("pause");
return 0;
}
I think I just need to change the if.. so if anyone can help me I would appreciate.
after all if you allow to enter 20 point your arrays xp and yp should have a size of 20, another advice if it's not a school work is using the structers, for solving your problem this is the code for fix it
bool b;
for (ic = 0; ic < m; ic++)
{
b=true;
for (c = 0; c < k; c++)
{
d = sqrtf((x[c] - xp[ic]) * (x[c] - xp[ic]) + (y[c] - yp[ic]) * (y[c] - yp[ic]));
b=b&&(d < r[c]);
}
if(b)
cout << "This point lies "<< 1 + ic << " ";
cout << endl;
}
Testing one point against many circles:
bool inCircle=true;
for (c = 0; c < k; c++)
{
d = sqrtf((x[c] - xp[ic]) * (x[c] - xp[ic]) + (y[c] - yp[ic]) * (y[c] - yp[ic]));
if (d > r[c])
{
inCircle = false;
cout << "the point is outside circle " << c << endl;
break; // this is not strictly needed
}
}
if(inCircle)
cout << "the point is inside all of the circles" << endl;
Once you have this working perfectly, you can put a loop around it to test many points.
I trying to create a program that receives and stores information about in a dynamic array of structures. And the program should sort and display the teams above average, average and below avaerage. This is my code so far. . So what I'm doing is I receive the user input the check the input before storing it in dynamic structure array. Then finally I display all the information stored in the struct. Here's the output that i'm currently getting and I'm not sure why i'm getting this negative numbers.any ideas why?
Thanks
How many teams do you want to store? 2
Enter the name of the team 1:Vikings
Enter the team 1 percentage: 90
Enter the name of the team 2:PackersGreen Bay Packers
Enter the team 2 percentage: 80
Above Average :
Vikings 90%
PackersGreen Bay Packers 80%
Average :
5.00136e-317%
None
Below Average :
None
9.25737e-306%
Here's my code.
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main()
{
struct aboveAverage
{
string name9;
double percentage1;
};
struct average
{
string name10;
double percentage2;
};
struct belowAverage
{
string name11;
double percentage3;
};
int numOfteams;
double userInput;
cout << "How many teams do you want to store? ";
cin >> numOfteams;
cin.get();
aboveAverage * arrayOfAboveAverage = new aboveAverage[numOfteams];
average * arrayOfAverage = new average[numOfteams];
belowAverage * arrayOfbelowAverage = new belowAverage[numOfteams];
for (int i = 0; i < numOfteams; i++)
{
start:
int x = i + 1;
string name5;
cout << "Enter the name of the team " << x << ":";
getline(cin, name5);
cout << "Enter the team " << x << " percentage: ";
cin >> userInput;
cin.get();
if (userInput >= 66 && userInput <= 100)
{
arrayOfAboveAverage[i].percentage1 = userInput;
arrayOfAboveAverage[i].name9 = name5;
}
else if (userInput <= 66 && userInput >= 33)
{
arrayOfAverage[i].name10 = name5;
arrayOfAverage[i].percentage2 = userInput;
}
else if (userInput <= 33 && userInput >= 0)
{
arrayOfbelowAverage[i].name11 = name5;
arrayOfbelowAverage[i].percentage3 = userInput;
}
else
{
cout << "Percent cannot be greater than 100" << endl;
goto start;
}
}
cout << "Above Average :" << endl;
for (int j = 0; j < numOfteams; j++)
{
if (arrayOfAboveAverage[j].percentage1 != NULL ||
arrayOfAboveAverage[j].name9 != "")
{
cout << arrayOfAboveAverage[j].name9 <<" ";
cout << arrayOfAboveAverage[j].percentage1 <<"%"<< endl;
}
else
{
cout << "None" << endl;
}
}
cout << "Average :" << endl;
for (int j = 0; j < numOfteams; j++)
{
if (arrayOfAverage[j].percentage2 > 0 ||
arrayOfAverage[j].name10 != "")
{
cout << arrayOfAverage[j].name10 <<" ";
cout << arrayOfAverage[j].percentage2 <<"%"<<endl;
}
else
{
cout << "None" << endl;
}
}
cout << "Below Average : "<< endl;
for (int k = 0; k < numOfteams; k++)
{
if (arrayOfbelowAverage[k].percentage3 > 0 ||
arrayOfbelowAverage[k].name11 != "")
{
cout << arrayOfbelowAverage[k].name11 << " ";
cout << arrayOfbelowAverage[k].percentage3 <<"%"<< endl;
}
else
{
cout << "None" << endl;
}
}
delete[] arrayOfAboveAverage;
delete[] arrayOfAverage;
delete[] arrayOfbelowAverage;
return 0;
}
The problem is in the following test
if (arrayOfAverage[j].percentage2 > 0 ||
arrayOfAverage[j].name10 != "")
When arrayOfAverage is uninitialized (as in your case) name10 is initialized with the default value for a std::string (the empty string) but the value for percentage2 (a double) is undefined.
You test both values with "or", not "and", so if percentage2 is initialized with a positive value (by example: 5.00136e-317) you enter in the true case.
Suggestion: when there is a useful value, the name10 value isn't empty, so ignore percentage2 and modify the test as follows
if ( ! arrayOfAverage[j].name10.empty() )
Same problem with the preceding
if (arrayOfAboveAverage[j].percentage1 != NULL ||
arrayOfAboveAverage[j].name9 != "")
and the following test
if (arrayOfbelowAverage[k].percentage3 > 0 ||
arrayOfbelowAverage[k].name11 != "")
My suggestion is to modify they as follows
if ( ! arrayOfAboveAverage[j].name9.empty() )
// ...
if ( ! arrayOfBelowAverage[j].name11.empty() )
Is this possible?
I'm making a directed weighted graph, using an adjacency matrix. Is it possible to have two weights using a matrix? I can visualize how to do this using an adjacency list, but that would entail rewriting all my code.
Here's the entirety of my code for this project. Yes, this is for school. No, I'm not asking you to do the work for me. I just can't seem to wrap my head around having two weights.
So basically, what I'm trying to do here is give the program two weights. I'll manage how to do the search and the actual cost calculations, I just can't figure out how I'm supposed to store two weights like this. The two weights are the time a train departs, and when it arrives. After that, I'll calculate the cost/path/etc. based on those two weights.
Can I have a matrix with two weights? How do I do that? I don't think a 3D matrix is what this lesson had in mind, though I think that would work (my idea being having a 3D matrix where z is just 2 deep so that I can store another integer "behind" the first one). I'd rather not, though, if possible.
As you can see, I mistook the purpose of the assignment and thought that just finding the difference between the two times and then storing that as the weight would work. But I need to know the difference between the departure of node x and the arrival of node y. So I think I need to pass those into the matrix and then calculate when I'm doing djikstra's to get the path cost.
Any ideas?
#include <iostream>
#include <iomanip>
#include <fstream>
#define MAX_SIZE 100
#define INFINITY 999999999
using namespace std;
class graph_matrix
{
public:
graph_matrix();
graph_matrix(int, int);
void setEdge(int, int, int);
void djikstra(int, int);
private:
int nodeCount;
int edgeCount;
int **matrix;
};
void graph_matrix::djikstra(int source, int destination)
{
int distances[nodeCount];
int minNode, minDistance;
bool vertexSet[nodeCount];
for(int i=0; i<nodeCount; i++)
{
distances[i] = INFINITY;
vertexSet[i] = false;
}
distances[source] = 0;
for(int i = 0; i<nodeCount-1; i++)
{
minNode = INFINITY;
minDistance = INFINITY;
for(int vert = 0; vert<nodeCount; vert++)
{
if(vertexSet[vert] == false && distances[vert] <= minDistance)
{
minDistance = distances[vert];
minNode = vert;
}
}
vertexSet[minNode] = true;
for(int vert = 0; vert<nodeCount; vert++)
{
if(vertexSet[vert] == false && matrix[minNode][vert])
{
if(distances[minNode] != INFINITY && distances[minNode] + matrix[minNode][vert] < distances[vert])
{
distances[vert] = distances[minNode] + matrix[minNode][vert];
}
}
}
}
if(distances[destination] < 60)
{
cout << distances[destination] << " minutes." << endl;
}
else if(distances[destination] > 60)
{
cout << (distances[destination] - distances[destination]%60)/60 << " hours and " << distances[destination]%60 << " minutes." << endl;
}
}
graph_matrix::graph_matrix()
{
nodeCount = 0;
edgeCount = 0;
matrix = NULL;
}
graph_matrix::graph_matrix(int nodes, int edges)
{
nodeCount = nodes + 1;
edgeCount = edges;
matrix = new int *[nodeCount];
for (int i = 0; i <= nodeCount; i++)
matrix[i] = new int[nodeCount];
for (int i = 0; i < nodeCount; i++)
{
for (int x = 0; x < nodeCount; x++)
matrix[i][x] = 0;
}
}
void graph_matrix::setEdge(int source, int destination, int weight)
{
matrix[source][destination] = weight;
}
int main()
{
ifstream file;
int statNumber, departStat, arriveStat, departTime, arriveTime, travelTime;
string statName[MAX_SIZE];
graph_matrix *gm = NULL;
file.open("stations.dat");
int stations = 0; //nodes
int tracks = 0; //edges
while(file >> statNumber)
{
file >> statName[statNumber];
stations++;
}
file.close();
file.open("trains.dat");
while(file >> departStat)
{
file >> departStat;//I tried just using 'file;' here, but it didn't work. I didn't see any harm in passing it to a variable, though.
file >> departStat;
file >> departStat;
tracks++;
//I'm sure this is the least elegant way of doing this, but this is what my brain came up with
}
file.close();
file.open("trains.dat");
gm = new graph_matrix(stations, tracks);
while(file >> departStat)
{
file >> arriveStat;
file >> departTime;
file >> arriveTime;
travelTime = arriveTime - departTime; //At first, I thought this is what I needed.
gm->setEdge(departStat, arriveStat, travelTime);
}
file.close();
int menuin, numberin, departin, arrivein;
string stationin;
bool done = false;
cout << "---------------------------------------------" << endl;
cout << " TRAIN MATE 3000 " << endl;
cout << "---------------------------------------------" << endl << endl << endl;
while(!done)
{
cout << "Options" << endl;
cout << "(1) - Look up station by number" << endl;
cout << "(2) - Look up station by name" << endl;
cout << "(3) - Find nonstop train" << endl;
cout << "(4) - Is service available" << endl;
cout << "(5) - Shortest ride time" << endl;
cout << "(6) - Quit" << endl << endl;
cout << "?: ";
cin >> menuin;
cout << endl;
switch (menuin)
{
case 1:
{
cout << ">Enter station number: ";
cin >> numberin;
cout << endl << ">>Station " << numberin << ": " << statName[numberin] << endl << endl;
break;
}
case 2:
{
cout << ">Enter station name: ";
cin >> stationin;
for(int i=0; i<=stations; i++)
{
if(stationin.compare(statName[i]) == 0)
{
cout << endl << ">>Station " << i << ": " << statName[i] << endl << endl;
}
}
break;
}
case 3:
{
cout << ">Enter departure station number: ";
cin >> departin;
cout << ">Enter arrival station number: ";
cin >> arrivein;
//do something to find if there's an edge
break;
}
case 4:
{
cout << ">Enter departure station number: ";
cin >> departin;
cout << ">Enter arrival station number: ";
cin >> arrivein;
//do something to find if there's a path
break;
}
case 5:
{
cout << ">Enter departure station number: ";
cin >> departin;
cout << ">Enter arrival station number: ";
cin >> arrivein;
cout << endl << ">>To go from " << statName[departin] << " to "<< statName[arrivein] << ", you will need to ride the train for ";
gm->djikstra(departin, arrivein);
cout << endl;
break;
}
case 6:
{
done = true;
break;
}
}
}
}
Sorry my main is pretty long. Don't worry about any of that. I'm just asking about the matrix itself, but I figured I'd give the whole context.
I'm a relatively new learner to C++ and I've been having some trouble. If you guys read the title, this is a homework problem (just letting you guys know out there) and I'm not really sure as to where my error is. Using GIT Bash, I can't see why this isn't compiling (or maybe i just don't know how to read it). I feel like i've touched upon all the bases and would appreciate a quick look over to see if my mistake is blaringly obvious. I've done a couple looks through stackoverflow and so the inputting values into a vector was used from another post but i've modified it a bit. In addition, I added in a sort for the vector from smallest to largest.
Also, how can I change the for statement to allow for variable #'s in the vector?
#include <iostream>
#include <vector>
using namespace std;
double showMedian(const vector<int> & vecmedian, int size)
{
int middle;
double average, median;
middle = size / 2.0;
if (size % 2 == 0)
{
median = (vecmedian[middle] + vecmedian[middle + 1]) / 2.0;
cout << "The median is: " << average << endl;
}
else
{
median = vecmedian[middle + 0] / 1.0;
cout << "The median is: " << median << endl;
}
return median;
}
int main()
{
int n,input, i;
vector<int> vecmedian;
vector<int>::iterator itr;
cout << "Enter the amount of numbers: ";
cin >> n;
cout << "Enter your numbers to be evaluated: " << endl;
while (vecmedian.size() < n && cin >> input){
vecmedian.push_back(input);
}
for(i = 1; i < 10; ++i){
for(itr = vecmedian.begin(); itr != vecmedian.end(); ++itr){
if(vecmedian[i] < *itr){
vecmedian.insert(itr, vecmedian[i]);
break;
}
}
if(itr == vecmedian.end())
vecmedian.push_back(vecmedian[i]);
}
showMedian();
return 0;
}
Point 1
When making function prototypes, you need to keep them consistent with the actual definition of the function.
You have:
void showMedian();
As a function-prototype but you have:
double showMedian(int *vecmedian, int size)
As the actual definition. They both need to be consistent.
Since you have not declared an array, maybe change the parameters of showMedian to:
double showMedian(const vector<int> & vecmedian, int size)
Point 2
if(nums[i] < *itr)
Where is nums declared?
Point 3
If you want to use the definition of showMedian, then use the parameters that it uses assuming you made the changes above (and assuming n is size).
showMedian(vecmedian, n);
Edit
With all the consulting in the comment section and the new updated OP Question, here is a fairly solid program which finds the median in a vector:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
double showMedian(const vector<double> & vecmedian, int num);
int main()
{
unsigned int n;
double input;
vector<double> vecmedian;
// cout << "Enter the amount of numbers: ";
do {
cout << "Enter the amount of numbers: ";
while(!(cin >> n)){
cout << "Wrong input" << endl;
cout << "Enter the amount of numbers: ";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
if (n == 0)
{
cout << "Invalid, size must be greater than 0" << endl;
}
} while (n == 0);
// cout << "Enter your numbers to be evaluated: " << endl;
for (int i = 1; i <= n; ++i)
{
cout << "Enter number here (" << ((n + 1) - i) << " number/s remaining): ";
while(!(cin >> input)){
cout << "Wrong input" << endl;
cout << "Enter number here (" << ((n + 1) - i) << " number/s remaining): ";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
vecmedian.push_back(input);
}
// while (vecmedian.size() < n && cin >> input){
// vecmedian.push_back(input);
// }
sort(vecmedian.begin(), vecmedian.end());
showMedian(vecmedian, vecmedian.size());
return 0;
}
double showMedian(const vector<double> & vecmedian, int num)
{
int middle;
double median;
middle = (num / 2);
if (num % 2)
median = vecmedian[middle];
else
median = (vecmedian[middle - 1] + vecmedian[middle]) / 2.0;
cout << "The median is: " << median << endl;
return median;
}