This question already has answers here:
What are the dangers of uninitialised variables?
(4 answers)
What happens to uninitialized variables? C++ [duplicate]
(3 answers)
Closed 7 months ago.
in a function in my code, I used two separate for-loops to calculate the total sales for each brand but the output of the second for-loop is wrong.
this is my output :
Number of Sales by Car Brand (2001-2010)
----------------------------------------
Year Proton Perodua Total
----------------------------------------
2001 76568 99342 175910
2002 92539 181903 274442
2003 93567 177422 270989
2004 87993 99856 187849
2005 101234 188230 289464
2006 103975 168911 272886
2007 100672 200152 300824
2008 99456 180453 279909
2009 100821 199654 300475
2010 109716 200894 310610
----------------------------------------
Average 96654.1 200743 266337
----------------------------------------
LOWEST : Proton (76568) in year 2001
HIGHEST : Perodua (200894) in year 2010
this is the correct output :
Number of Sales by Car Brand (2001-2010)
----------------------------------------
Year Proton Perodua Total
----------------------------------------
2001 76568 99342 175910
2002 92539 181903 274442
2003 93567 177422 270989
2004 87993 99856 187849
2005 101234 188230 289464
2006 103975 168911 272886
2007 100672 200152 300824
2008 99456 180453 279909
2009 100821 199654 300475
2010 109716 200894 310610
----------------------------------------
Average 96654.1 169682 266336
----------------------------------------
LOWEST: Proton (76568) in year 2001
HIGHEST: Perodua (200894) in year 2010
the actual average of the total sales for Perodua :
169682
the value im getting :
200743
this is the part having issues :
Average calcAvrg(int sales_proton[10], int sales_perodua[10])
{
int sum_proton, sum_perodua;
double avg_proton, avg_perodua;
for(int i = 0; i < 10; i++)
{
sum_proton = sum_proton + sales_proton[i];
}
avg_proton = sum_proton / 10.00;
for(int count = 0; count < 10; count++)
{
sum_perodua = sum_perodua + sales_perodua[count];
}
avg_perodua = sum_perodua / 10.00;
Average avrg;
avrg.avrg_proton = avg_proton;
avrg.avrg_perodua = avg_perodua;
return avrg;
}
here's my full code :
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
struct Average
{
double avrg_proton;
double avrg_perodua;
};
void getInput(int [], int [], int []);
Average calcAvrg(int [], int []);
void dispAnalysis(int [], int [], int []);
void dispOutput(int [], int [], int []);
int main()
{
int year[10];
int num_sales_proton[10];
int num_sales_perodua[10];
getInput(year, num_sales_proton, num_sales_perodua);
dispOutput(year, num_sales_proton, num_sales_perodua);
return 0;
}
void getInput(int yr[10], int sales_proton[10], int sales_perodua[10])
{
ifstream textFile;
textFile.open("input.txt");
if (!textFile)
{
cout << "ERROR! The " << textFile << " file cannot be found or read!" << endl;
exit(EXIT_FAILURE);
}
int i = 0;
while(i < 10 && textFile >> yr[i] >> sales_proton[i] >> sales_perodua[i])
{
i += 1;
}
textFile.close();
}
Average calcAvrg(int sales_proton[10], int sales_perodua[10])
{
int sum_proton, sum_perodua;
double avg_proton, avg_perodua;
for(int i = 0; i < 10; i++)
{
sum_proton = sum_proton + sales_proton[i];
}
avg_proton = sum_proton / 10.00;
for(int count = 0; count < 10; count++)
{
sum_perodua = sum_perodua + sales_perodua[count];
}
avg_perodua = sum_perodua / 10.00;
Average avrg;
avrg.avrg_proton = avg_proton;
avrg.avrg_perodua = avg_perodua;
return avrg;
}
void dispAnalysis(int yr[10], int sales_proton[10], int sales_perodua[10])
{
int lowest, highest, lowest_proton = sales_proton[0], highest_proton = sales_proton[0], lowest_perodua = sales_perodua[0], highest_perodua = sales_perodua[0];
int year_lowest, year_highest, year_lowest_proton = yr[0], year_highest_proton = yr[0], year_lowest_perodua = yr[0], year_highest_perodua = yr[0];
string brand_lowest, brand_highest;
for(int i = 0; i < 10; i++)
{
if(sales_proton[i] < lowest_proton)
{
lowest_proton = sales_proton[i];
year_lowest_proton = yr[i];
}
if(sales_proton[i] > highest_proton)
{
highest_proton = sales_proton[i];
year_highest_proton = yr[i];
}
}
for(int i = 0; i < 10; i++)
{
if(sales_perodua[i] < lowest_perodua)
{
lowest_perodua = sales_perodua[i];
year_lowest_perodua = yr[i];
}
if(sales_perodua[i] > highest_perodua)
{
highest_perodua = sales_perodua[i];
year_highest_perodua = yr[i];
}
}
if(lowest_proton < lowest_perodua)
{
lowest = lowest_proton;
brand_lowest = "Proton";
year_lowest = year_lowest_proton;
}
else
{
lowest = lowest_perodua;
brand_lowest = "Perodua";
year_lowest = year_lowest_perodua;
}
if(highest_proton > highest_perodua)
{
highest = highest_proton;
brand_highest = "Proton";
year_highest = year_highest_proton;
}
else
{
highest = highest_perodua;
brand_highest = "Perodua";
year_highest = year_highest_perodua;
}
cout << "LOWEST : " << brand_lowest << " (" << lowest << ") in year " << year_lowest << endl;
cout << "HIGHEST : " << brand_highest << " (" << highest << ") in year " << year_highest << endl;
}
void dispOutput(int yr[10], int sales_proton[10], int sales_perodua[10])
{
int total_per_year[10], overall_total;
double avrg_total;
cout << "Number of Sales by Car Brand (2001-2010)" << endl;
cout << "----------------------------------------" << endl;
cout << setw(4) << "Year";
cout << setw(6) << " Proton";
cout << setw(6) << " Perodua";
cout << setw(6) << " Total" << endl;
cout << "----------------------------------------" << endl;
for(int i = 0; i < 10; i++)
{
total_per_year[i] = sales_proton[i] + sales_perodua[i];
}
for(int count = 0; count < 10; count++)
{
cout << setw(4) << right << yr[count] << " ";
cout << setw(6) << right << sales_proton[count] << " ";
cout << setw(6) << right << sales_perodua[count] << " ";
cout << setw(6) << right << total_per_year[count]<< endl;
}
cout << "----------------------------------------" << endl;
Average a = calcAvrg(sales_proton, sales_perodua);
for(int i = 0; i < 10; i++)
{
overall_total = overall_total + total_per_year[i];
}
avrg_total = overall_total / 10.00;
cout << "Average " << a.avrg_proton << " " << a.avrg_perodua << " " << avrg_total << endl;
cout << "----------------------------------------" << endl;
dispAnalysis(yr, sales_proton, sales_perodua);
}
I tried removing the first for-loop and the output came out correct so I think the problem is what values the loop is adding for the total sales of Perodua. I am not sure how to go about this as I'm pretty new to C++ so it would be great if someone could help
Thanks
You forgot to initialize the variables sum_proton and sum_perodua, so you are adding your values to their indeterminate values.
Initialize the variables before adding like this:
int sum_proton = 0, sum_perodua = 0;
The problem is that you're using uninitialized variable in sum_proton in sum_proton = sum_proton + sales_proton[i]; leading to undefined behavior.
To solve this, initialize built in types:
int sum_proton =0, sum_perodua =0;
double avg_proton =0, avg_perodua =0;
Related
I wrote a code to manage a coffee machine,
I have a function findC that finds the cheapest capsule in the capsule array
a different function of mine findVP that is supposed to use the findC function's output as variables. however, when I pass the variables mp, ind = findC(prices_copy, quantities_copy, SIZE);
and print them it passes them as 0;
but the 2nd cout : cout << findC(prices_copy, quantities_copy, SIZE); prints the correct output.
why is this ? and how can I pass the output of the function to another
/******************************************************************************
Online C++ Compiler.
Code, Compile, Run and Debug C++ program online.
Write your code in this editor and press "Run" button to compile and execute it.
*******************************************************************************/
// Example program
#include <iostream>
#include <string>
#include <bits/stdc++.h>
using namespace std;
#define SLEEVE 10
#define SIZE 10
#define N 5
#define BUDGET 70
//int CapsuleKind[10] = {"JOE","MAC","NES","jamaica","brazil","columbia","MOJO","CLUB","JHON","COF"};
float findMostExpensiveCapsule( float prices[], int size ) // 1
{
float max = prices[0];
int count = 0;
for(int i = 1; i < size; i++)
{
if (prices[i] > max)
{
max = prices[i];
}
}
cout << "The maximum price " << max << " is found on indexes: " ;
for (int i = 0; i < size; i++)
{
if (prices[i] == max)
{
cout << i << " ";
count++;
}
}
cout << endl;
cout << "The maximum number appears " << count << " times." << endl;
return max;
}
int findStrongestCapsuleInStock( int quantities[], int size, int sleeve ) // 2
{
return 0;
}
void SellCapsules( int quantities[], int Qty, int index) // 10
{
quantities[index] = quantities[index] - Qty;
cout << "SOLD " << Qty << " capsules to the Customer, the total now is: " << quantities[index] << endl;
}
float findC( float prices[],int quantities[], int size ) // 9
{
float min = 99999;
int count = 0;
float index=0;
//sort(prices, arr + n);
for(int i = 0; i < size; i++)
{
if (quantities[i] >= SLEEVE)
{
if(prices[i] < min){
min = prices[i];
index= i;
}
else continue;
}
}
cout <<"the minimum price is : " << min << " ---- the index is : " << index << endl;
return min, index;
}
void findCheapestSleeve( float prices[],int quantities[], int size )
{
float min = prices[0];
int count = 0;
int index=0;
for(int i = 0; i < size; i++)
{
if (prices[i] < min)
{
if(quantities[i] > SLEEVE){
min = prices[i];
index= i;
}
else continue;
}
}
cout <<"the minimum price is : " << min << " ---- the index is : " << index << endl;
}
void showAllCapsulesInStock( int quantities[], float prices[], int size, int sleeve) // 3
{
for (int i = 0; i < size; i++)
{
cout << "capsule kind: " << i << " ---- sleeves available : " << (quantities[i]/sleeve) << " ---- price(for 1 sleeve): " << (prices[i]*sleeve)<< endl;
}
}
float findVP( float prices[], int quantities[], int size, float nis, int sleeve ) //4
{
float mp=0;
float ind =0;
float prices_copy[size];
int quantities_copy[size];
for(int i=0; i<size; i++){
prices_copy[i] = prices[i];
quantities_copy[i] = quantities[i];
}
mp, ind = findC(prices_copy, quantities_copy, SIZE);
cout << "The lowest price sleeve is: " << mp * 10 << " --- the capsule kind is: " << ind <<endl;
cout << findC(prices_copy, quantities_copy, SIZE);
}
void findValueForMoneyPackage( float prices[], int quantities[], int size, float nis, int sleeve )
{
int sleeve_num[size];
float sleeve_price[size];
float min=0;
int index = 0;
int counter=0;
float quant = 0;
for (int i=0; i < size; i++)
{
sleeve_num[i] = (quantities[i]/sleeve);
sleeve_price[i] = (prices[i] * sleeve);
}
//min, quant = findCheapestSleeve(sleeve_price, quantities, 10);
cout << "the cheapest sleeve costs : " << min << " and its of kind :" << quant << endl;
}
void addMoreCapsules( int quantities[], int size ) // 5
{
char answer;
int plus;
for (int i = 0; i < size; i++)
{
cout << "do you want to add capsules to capsule kind " << i << "? (Y/N) " << endl;
cin >> answer;
if (answer == 'Y')
{
cout << "How many capsules do you want to add (inter a number) " << endl;
cin >> plus;
if (plus > 0)
{
quantities[i] = quantities[i] + plus;
cout << "Added " << plus << " capsules to the inventory, the total now is: " << quantities[i] << endl;
}
}
else
{
continue;
}
}
}
// Driver Code
int main()
{
bool flag = false;
int option;
float prices[] = { 1.2, 2.2, 2.5, 1.7, 2.2, 3, 2.8, 2.5, 2.9, 3.7 };
int quantities[] = { 14, 22, 25, 13, 22, 33, 50, 60, 33, 25 };
while (flag != true)
{
cout << "Please choose an option , has to be a number 1-6" << endl;
cin >> option;
if (option == 1)
{
findMostExpensiveCapsule(prices,SIZE);
}
else if ( option == 3)
{
showAllCapsulesInStock(quantities, prices, SIZE, 10);
}
else if (option == 4){
findVP(prices, quantities, SIZE, BUDGET, SLEEVE);
}
else if(option == 5){
addMoreCapsules(quantities,SIZE);
}
else if(option == 9){
findC(prices, quantities, SIZE);
}
else
{
flag = true;
}
}
cout << "GoodBye!" << endl;
return 0;
}
This
return min, index;
doesn't do what you think it does. You obviously think it's going to return two values. But actually it just returns index.
This
mp, ind = findC(prices_copy, quantities_copy, SIZE);
doesn't do what you think it does. You obviously think it's going to assign the two returned values from findC to the variables mp and ind. But actually it's going to return the single value returned by findC to the variable ind and ignore mp.
If you want to know precisely what these constructs do then look up the comma operator, but I guess the moral of the story is that just because you can get some plausible looking code to compile it doesn't mean that it's going to do what you expected it to do.
So the real question is how to return two values from a function in C++. There are actually several possible approaches. Here's a question that reviews some of them, Returning multiple values from a C++ function.
I am working on this university project and I have 2-3 issues. I want to get them done 1 by 1.
My first question is about one of my getter/setter functions.
Here are the class's attributes:
I got getters and setters for each attribute of the class, and a view function that shows the attributes of a class object
class Game{
private:
string gameName;
float gamePrice;
int gameNoPlatforms;
string *gamePlatforms;
int gameNoSitesRating;
int *gameRatings;
int gameSales[19];
string gameLaunchers[5];
}
Those 2 are my get/set function for the atribute * string gamePlatforms:
void setGamePlatforms(string *newGamePlatforms, int newGameNoPlatforms)
{
if (this->gamePlatforms != NULL)
{
delete[] this->gamePlatforms;
}
if (newGameNoPlatforms > 0 )
{
this->gameNoPlatforms = newGameNoPlatforms;
this->gamePlatforms = new string[this->gameNoPlatforms];
for (int i = 0; i < this->gameNoPlatforms; i++)
{
this->gamePlatforms[i] = newGamePlatforms[i];
}
}
else cout << "The number of new game platforms can't be negative. "<< endl;
}
string *getGamePlatforms()
{
return this->gamePlatforms;
}
And this is the input that i tried to test on:
int main(){
Game g1;
int noPlatforms = 10;
string*model = new string[noPlatforms];
for (int i = 0; i < noPlatforms; i++)
{
model[i] = "Platform " + to_string(i+10);
}
g1.setGamePlatforms(model, noPlatforms); //-> not working
g1.setGamePlatforms(model, noPlatforms);
cout << g1.getGamePlatforms();
return 0;
}
And for me it is returning a weird value. I think it is an address. What have I done wrong?
Edit: the entire class:
class Game{
private: string gameName;
float gamePrice;
int gameNoPlatforms;
string *gamePlatforms;
int gameNoSitesRating;
int *gameRatings;
int gameSales[19];
string gameLaunchers[5];
public:
// Constructor1 fara parametrii pt game
Game():gameReleaseYear(2000)
{
this->gameName = "Counter-Strike";
this->gamePrice = 20;
this->gameNoPlatforms = 10;
this->gamePlatforms = new string[this->gameNoPlatforms];
for (int i = 0; i < this->gameNoPlatforms; i++)
{
this->gamePlatforms[i] = "Platform" + to_string(i+1);
}
this->gameNoSitesRating = 5;
this->gameRatings = new int[this->gameNoSitesRating];
for (int i = 0; i < this->gameNoSitesRating; i++)
this->gameRatings[i] = i + 1;
for (int i = 1; i < 19; i++)
{
this->gameSales[i] = i + 2;
}
for (int i = 1; i < 5; i++)
{
this->gameLaunchers[i] = "Launcher" + to_string(i);
}
this->noGames++; //incrementare nr games
}
// Constructor cu parametrii pt game
Game(string gameNameP, float gamePriceP, int gameNoPlatformsP, string *gamePlatformsP, int gameNoSitesRatingP, int *gameRatingsP, int gameSalesP[19], string gameLaunchersP[5]) :gameReleaseYear(2005)
{
this->gameName = gameNameP;
this->gamePrice = gamePriceP;
this->gameNoPlatforms = gameNoPlatformsP;
this->gamePlatforms = new string[this->gameNoPlatforms];
for (int i = 0; i < this->gameNoPlatforms; i++)
{
gamePlatforms[i] = gamePlatformsP[i];
}
this->gameNoSitesRating = gameNoSitesRatingP;
this->gameRatings = new int[this->gameNoSitesRating];
for (int i = 0; i < this->gameNoSitesRating; i++)
{
gameRatings[i] = gameRatingsP[i];
}
for (int i = 0; i < 19; i++)
{
gameSales[i] = gameSalesP[i];
}
for (int i = 0; i < 5; i++)
{
gameLaunchers[i] = gameLaunchersP[i];
}
}
// Destructor pt game
~Game()
{
if (this->gamePlatforms != NULL)
delete[] this->gamePlatforms;
if (this->gameRatings != NULL)
delete[] this->gameRatings;
noGames--; // decrementare nr games
}
// Functie de afisare pentru game
void view()
{
cout << "For the game: " <<' '<< this->gameName << " we have the following details: " << endl;
cout << endl;
cout << "The release year for the game was: " << this->gameReleaseYear << endl;
cout << endl;
cout << "The game is sold at a full price of: " << this->gamePrice << " euroes" << endl;
cout << endl;
cout << "The number of sites that are rating this game is: " << this -> gameNoSitesRating << " and the ratings are: " << endl;
cout << endl;
for (int i = 0; i < this->gameNoSitesRating; i++)
{ if(this->gameRatings[i]+i >10)
cout << "The no " << i + 1 << " site is rating the game as " << 10 << " stars out of 10 " << endl;
else
cout << "The no " << i+1 << " site is rating the game as " << this->gameRatings[i] << " stars out of 10 " << endl;
}
cout << endl;
cout << "The sales of the game from the release year since now are: " << endl;
for (int i = 1; i < 19; i++)
{
cout << "For the year " << i << " the sales estimate at " << gameSales[i] << " millions" << endl;
}
cout << endl;
cout << "The launchers that support the game are: " << endl;
for (int i = 1; i < 5; i++)
{
cout << gameLaunchers[i] << ' ' << endl;
}
cout << "The game is currently running on " << this->gameNoPlatforms << " number of platforms, and those platforms are: " << endl;
cout << endl;
for (int i = 0; i < this->gameNoPlatforms; i++)
{
cout << this->gamePlatforms[i] << endl;
}
}
// functiile accesor getters
string getGameName()
{
return this->gameName;
}
float getGamePrice()
{
return this->gamePrice;
}
int getGameNoPlatforms()
{
return this->gameNoPlatforms;
}
int getNoSitesRating()
{
return this->gameNoSitesRating;
}
string *getGamePlatforms()
{
return this->gamePlatforms;
}
int *getGameRatings()
{
return this->gameRatings;
}
string *getGameLaunchers()
{
return this->gameLaunchers;
}
//functiile accesor setters
void setGameName(string newGameName) //testat pt input valid si invalid
{ if(newGameName != gameName)
this->gameName = newGameName;
else cout << "This is the actual name of the game, no modify is required.";
}
void setGamePrice(float newPrice) //testat pt input valid si invalid;
{ if(newPrice>0)
this->gamePrice = newPrice;
else cout << "The price can't be negative." << endl;
}
void setGameNoPlatforms(int newNoPlatforms) //testat pentru input valid, input mai mare ca 5 si negativ
{ if(newNoPlatforms>0 && newNoPlatforms <5)
this->gameNoPlatforms = newNoPlatforms;
else cout << "The number of platforms can't be negative and must be less than 5, since this is the maximum number of existing platforms." << endl;
}
void setGameNoSitesRating(int newNoSites) //testat pentru input valid, input negativ, input mai mare decat 15
{ if(newNoSites>0 && newNoSites<15)
this->gameNoSitesRating = newNoSites;
else cout << "The number of sites can't be negative nor greater than 15 since this is the maximum number of sites that our game is rated on." << endl;
}
void setGamePlatforms(string *newGamePlatforms, int newGameNoPlatforms) //testat pt input valid, returneaza adresa
{
if (this->gamePlatforms != NULL)
{
delete[] this->gamePlatforms;
}
if (newGameNoPlatforms > 0 ){
this->gameNoPlatforms = newGameNoPlatforms;
this->gamePlatforms = new string[this->gameNoPlatforms];
for (int i = 0; i < this->gameNoPlatforms; i++)
{
this->gamePlatforms[i] = newGamePlatforms[i];
}
}
else cout << "The number of new game platforms can't be negative. "<< endl;
}
void setGameRatings(int *newGameRatings, int newNoRatings) //testat pt valori valide, testat pt neNoRatings negativ;
{
if (newNoRatings < 0)
cout << "The new number of sites that are rating the game can't be negative";
else {
if (this->gameRatings != NULL)
{
delete[] this->gameRatings;
}
this->gameNoSitesRating = newNoRatings;
this->gameRatings = new int[this->gameNoSitesRating];
for (int i = 0; i < this->gameNoSitesRating; i++)
{
this->gameRatings[i] = newGameRatings[i];
}
}
}
void setGamesSales(int *newSales)
{
if (newSales != NULL)
{
for (int i = 0; i < 19; i++)
{
gameSales[i] = newSales[i];
}
}
else cout << "The sales can't be null." << endl;
}
void setLaucnhers(string *newLaunchers)
{
if (newLaunchers != NULL)
{
for (int i = 0; i < 5; i++)
{
gameLaunchers[i] = newLaunchers[i];
}
}
else cout << "The name of the new launchers can't be null." << endl;
}
//variabile static/const
const int gameReleaseYear;
static int noGames;
};
int Game::noGames = 0;
Try this:
int Game::getNumberOfPlatforms() const
{
return gameNoPlatforms;
}
And print them:
for(int i = 0; i < g1.getNumberOfPlatforms(); ++i)
cout << g1.getGamePlatforms()[i] << endl;
This is a problem given to me by my computer mentor and I am trying to explain the problem in simple words(I must remind you that my mentor has only taught me loops array structure. I cannot use class for this problem)
Take two matrix
Print the name of n students in one matrix
Print the id, marks in 5 subject of the students in another 2d
matrix (n*6)
Find the student who got the highest in the total of 5 subject and
print the student name with marks of each subject and his total
marks.(i think we have to us a structure)
For example: The highest marks is secured by :
Name;
id no;
marks in sub 1;
marks in sub 2;
marks in sub 3;
marks in sub 4;
marks in sub 5;
total;
Then print the id and the name of the student who got highest in
each subject
For example:
Subject 1 ID name
Subject 2 ID name .....
I have being able to solve it fully till point (3). but unable to print the person who got the highest in each subject ; and I am facing problem to print the person who got highest in each subject as I have to use many variables(I'm not using structure)
What I have tried so far:
#include <iostream>
using namespace std;
int main()
{
//making 1st array to print the names of the students
char x[500][1000];
int num, i;
cout << "Enter the number of student's data you want to input" << endl;
cin >> num;
cout << endl;
cout << "NAME LIST" << endl;
cout << endl;
for(i = 0; i < num + 1; i++)
{
cin.getline(x[i], 1000);
}
//making a 2nd array to print the id, marks in 5 subjects of the students
int y[num][6];
int a, b;
cout << endl;
cout << endl;
cout << "DETAILS OF THE STUDENT" << endl;
cout << endl;
for(int a = 0; a < num; a++)
{
cout << "ID no of student " << a + 1 << ":";
cin >> y[a][0];
cout << "Marks in subject 1:";
cin >> y[a][1];
cout << "Marks in subject 2:";
cin >> y[a][2];
cout << "Marks in subject 3:";
cin >> y[a][3];
cout << "Marks in subject 4:";
cin >> y[a][4];
cout << "Marks in subject 5:";
cin >> y[a][5];
cout << endl;
}
cout << endl;
cout << "The data you inputed:";
cout << endl;
for(a = 0; a < num; a++)
{
for(b = 0; b < 6; b++)
{
cout << y[a][b] << " ";
}
cout << endl;
}
cout << endl;
cout << endl;
//finding the member who got the highest marks
int s = 0;
int largestSum = 0;
for(a = 0; a < num; i++)
{
for(b = 0; b<6; b++)
{
s += y[a][b];
}
// check to see if we have computed a new larger sum and save it if we have.
if(s > largestSum)
{
largestSum = s;
}
}
cout << "largest sum: " << largestSum << endl;
return 0;
}
int s = 0; <- s needs to be reset to zero in each loop
int largestSum = 0;
for(a = 0; a<num; i++) <- loop doesn't break
{
for(b = 0; b<6; b++) <- b should start at 1
{
s += y[a][b];
}
if(s > largestSum)
{
largestSum = s;
}
}
i is incremented while a remains constant and the loop goes forever.
s is not reset to zero, so you sum all the values.
The first index at b = 0 is supposed to be student id, it should be skipped. Try instead:
int largestSum = 0;
for(a = 0; a < num; a++)
{
int s = 0;
for(b = 1; b < 6; b++)
s += y[a][b];
if(s > largestSum)
largestSum = s;
}
Here's something to go off of.
Note that I only made one matrix and put the Student objects in it.
#include <ctime>
#include <iostream>
#include <string>
#include <vector>
const std::vector<std::vector<std::string>> names = {
{"Ralph", "Gerald", "Henry", "Jessica", "Bob"},
{"Tara", "Tami", "Mike", "Loretta", "Jean"},
{"Jesse", "John", "Carl", "Josh", "Abby"},
{"Carson", "Don", "George", "Hillary", "David"},
{"Micah", "Charlie", "Maximus", "Leonidas", "Xerxes"}
};
int main()
{
time_t seconds;
time(&seconds);
srand((unsigned int)seconds);
struct Subjects
{
unsigned int subject[5] = {};
};
struct Student
{
Subjects sub;
std::string name;
int id;
Student() : name("nobody"), id(-1) {};
Student(const std::string& name, const unsigned int& id) : name(name), id(id) {}
};
Student stud_matrix[5][5] = {};
int count = 0;
for (size_t i = 0; i != 5; ++i)
{
for (size_t j = 0; j != 5; ++j)
{
stud_matrix[i][j].name = names[i][j];
stud_matrix[i][j].id = count;
++count;
}
}
std::cout << "All student names:\n";
for (size_t i = 0; i != 5; ++i)
{
for (size_t j = 0; j != 5; ++j)
{
std::cout << stud_matrix[i][j].name << ' ';
}
std::cout << std::endl;
}
std::cout << std::endl;
std::cout << "All student IDs:\n";
for (size_t i = 0; i != 5; ++i)
{
for (size_t j = 0; j != 5; ++j)
{
std::cout << stud_matrix[i][j].id << ' ';
}
std::cout << std::endl;
}
std::cout << std::endl;
for (size_t i = 0; i != 5; ++i)
{
for (size_t j = 0; j != 5; ++j)
{
stud_matrix[i][j].sub.subject[0] = (rand() % 100 + 1);
stud_matrix[i][j].sub.subject[1] = (rand() % 100 + 1);
stud_matrix[i][j].sub.subject[2] = (rand() % 100 + 1);
stud_matrix[i][j].sub.subject[3] = (rand() % 100 + 1);
stud_matrix[i][j].sub.subject[4] = (rand() % 100 + 1);
}
}
Student best_student;
unsigned int highest_grade = {};
for (size_t i = 0; i != 5; ++i)
{
for (size_t j = 0; j != 5; ++j)
{
if (stud_matrix[i][j].sub.subject[0] > highest_grade)
{
highest_grade = stud_matrix[i][j].sub.subject[0];
best_student = stud_matrix[i][j];
}
if (stud_matrix[i][j].sub.subject[1] > highest_grade)
{
highest_grade = stud_matrix[i][j].sub.subject[1];
best_student = stud_matrix[i][j];
}
if (stud_matrix[i][j].sub.subject[2] > highest_grade)
{
highest_grade = stud_matrix[i][j].sub.subject[2];
best_student = stud_matrix[i][j];
}
if (stud_matrix[i][j].sub.subject[3] > highest_grade)
{
highest_grade = stud_matrix[i][j].sub.subject[3];
best_student = stud_matrix[i][j];
}
if (stud_matrix[i][j].sub.subject[4] > highest_grade)
{
highest_grade = stud_matrix[i][j].sub.subject[4];
best_student = stud_matrix[i][j];
}
}
}
std::cout << "The highest scoring student in any one subject is: " << best_student.name << std::endl;
std::cout << "ID: " << best_student.id << std::endl;
std::cout << "Marks in sub1: " << best_student.sub.subject[0] << std::endl;
std::cout << "Marks in sub2: " << best_student.sub.subject[1] << std::endl;
std::cout << "Marks in sub3: " << best_student.sub.subject[2] << std::endl;
std::cout << "Marks in sub4: " << best_student.sub.subject[3] << std::endl;
std::cout << "Marks in sub5: " << best_student.sub.subject[4] << std::endl;
std::cout << "Total: " << best_student.sub.subject[0] + best_student.sub.subject[1] + best_student.sub.subject[2] +
best_student.sub.subject[3] + best_student.sub.subject[4] << std::endl;
std::cout << std::endl;
Student stud_sub1;
Student stud_sub2;
Student stud_sub3;
Student stud_sub4;
Student stud_sub5;
unsigned int high_sub1 = {};
unsigned int high_sub2 = {};
unsigned int high_sub3 = {};
unsigned int high_sub4 = {};
unsigned int high_sub5 = {};
for (size_t i = 0; i != 5; ++i)
{
for (size_t j = 0; j != 5; ++j)
{
if (stud_matrix[i][j].sub.subject[0] > high_sub1)
{
high_sub1 = stud_matrix[i][j].sub.subject[0];
stud_sub1 = stud_matrix[i][j];
}
if (stud_matrix[i][j].sub.subject[1] > high_sub2)
{
high_sub2 = stud_matrix[i][j].sub.subject[1];
stud_sub2 = stud_matrix[i][j];
}
if (stud_matrix[i][j].sub.subject[2] > high_sub3)
{
high_sub3 = stud_matrix[i][j].sub.subject[2];
stud_sub3 = stud_matrix[i][j];
}
if (stud_matrix[i][j].sub.subject[3] > high_sub4)
{
high_sub4 = stud_matrix[i][j].sub.subject[3];
stud_sub4 = stud_matrix[i][j];
}
if (stud_matrix[i][j].sub.subject[4] > high_sub5)
{
high_sub5 = stud_matrix[i][j].sub.subject[4];
stud_sub5 = stud_matrix[i][j];
}
}
}
std::cout << "Best of subject:\n";
std::cout << "Subject 1:\nID: " << stud_sub1.id << ' ' << stud_sub1.name << " Score: " << high_sub1 << std::endl;
std::cout << "Subject 2:\nID: " << stud_sub2.id << ' ' << stud_sub2.name << " Score: " << high_sub2 << std::endl;
std::cout << "Subject 3:\nID: " << stud_sub3.id << ' ' << stud_sub3.name << " Score: " << high_sub3 << std::endl;
std::cout << "Subject 4:\nID: " << stud_sub4.id << ' ' << stud_sub4.name << " Score: " << high_sub4 << std::endl;
std::cout << "Subject 5:\nID: " << stud_sub5.id << ' ' << stud_sub5.name << " Score: " << high_sub5 << std::endl;
system("pause");
return 0;
}
Sample Output:
All student names:
Ralph Gerald Henry Jessica Bob
Tara Tami Mike Loretta Jean
Jesse John Carl Josh Abby
Carson Don George Hillary David
Micah Charlie Maximus Leonidas Xerxes
All student IDs:
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24
The highest scoring student in any one subject is: Bob
ID: 4
Marks in sub1: 77
Marks in sub2: 67
Marks in sub3: 7
Marks in sub4: 99
Marks in sub5: 66
Total: 316
Best of subject:
Subject 1:
ID: 23 Leonidas Score: 95
Subject 2:
ID: 18 Hillary Score: 92
Subject 3:
ID: 19 David Score: 98
Subject 4:
ID: 4 Bob Score: 99
Subject 5:
ID: 22 Maximus Score: 98
I am having some trouble in my marked "Median" function. I am getting an error that says `Horse[10][double]' for array subscript. I am not sure how to fix this and I am looking for some friendly help.
#include <cstdlib>
#include <iostream>
#include <math.h>
/*
Name: Horses2
Author: Grant Birkinbine
Date: 03/12/14 18:25
Description: A program that modifies the Horses program
*/
//Start
using namespace std;
//Class
class Horse{
private:
string name ;
int lane;
double time;
public:
Horse(string hname , int hlane , double htime){
name = hname ;
lane = hlane ;
time = htime;
}
Horse(){
name = "" ;
lane = 0 ;
time = 0 ;
}
void setname(string hname){
name = hname;
}
void setlane(int hlane){
lane = hlane;
}
void settime(double htime){
time = htime;
}
string getname (){
return name ;
}
int getlane(){
return lane;
}
double gettime(){
return time;
}
void print(){
cout << "Horse Name: " << name << endl;
cout << "Horse Lane: " << lane << endl;
cout << "Horse Time: " << time << endl;
cout << endl;
}
};
//Main
void insertion_sort(Horse x[],int length);
int main(int argc, char *argv[])
{
cout << "Horse Race Results: " << endl << endl;
Horse ahorse[10];
ahorse[0] = Horse("American idol " , 1 , 45.41);
ahorse[1] = Horse("Bababooey " , 2 , 42.42);
ahorse[2] = Horse("Charlie Horse " , 3 , 40.94);
ahorse[3] = Horse("Dog Biscuit " , 4 , 43.55);
ahorse[4] = Horse("Echo " , 5 , 41.41);
ahorse[5] = Horse("Firefox " , 6 , 42.58);
ahorse[6] = Horse("Google " , 7 , 42.58);
ahorse[7] = Horse("Hoof-Hearted " , 8 , 44.57);
ahorse[8] = Horse("Ima Loozer " , 9 , 41.57);
ahorse[9] = Horse("Just Walking " , 10 , 50.00);
//Sorting
int length = 10;
insertion_sort(ahorse, length);
double avg;
double x;
double max;
double min;
avg=0;
x = 0;
int abovea = 4 ;
int belowa = 6 ;
int abovem = 4 ;
int belowm = 4 ;
//Average
for (int i =0 ; i<10 ; i++ ) {
x = x + ahorse[i].gettime() ;
}
avg = (x / 10);
//Max
for(int i = 0 ; i < 10 ; i++){
max = -1000;
if ( ahorse[i].gettime() > max){
max = ahorse[i].gettime();
}
}
//Min
for(int i = 0 ; i < 10; i ++){
min = 1000;
if ( ahorse[i].gettime() < min){
min = ahorse[1].gettime() ;
}
}
for(int i = 0; i < 10; i++){
ahorse[i].print() ;
}
//Median
double median;
if(ahorse[x].gettime() % 2 == 0){
median = (ahorse[10].gettime() / 2) + (ahorse[10].gettime() / 2 + 1) / 2;
}
else{
median = (ahorse[10].gettime() / 2) + 1;
}
cout << "Average: " << avg << endl;
cout << "Fastest Time: " << min << endl;
cout << "Slowest Time: " << max << endl;
cout << "# Above Mean: " << abovea << endl;
cout << "# Below mean: " << belowa << endl;
cout << "# Above median: " << abovem << endl;
cout << "# Below median: " << belowm << endl;
cout << endl;
system("PAUSE");
return EXIT_SUCCESS;
}
void insertion_sort(Horse x[],int length){
Horse key;
int i;
for(int j=1;j<length;j++)
{
key= x[j];
i=j-1;
while(x[i].gettime()>key.gettime() && i>=0)
{
x[i+1]=x[i];
i--;
}
x[i+1]=key;
}
}
First, you can't use a double to subscript an array, soahorse[x].gettime()won't work, arrays has to be subscripted using integers. Think about it, what element wouldahorse[9.5]refer to?
Second, the modulus operator%only works for integers. Use fmod if you want to do mod on double
Third, arrays are indexed starting from zero, so the access toahorse[10]in the median part is accessing the array outside it's bound and is an invalid memory access as the last element of theHorse ahorse[10]array isahorse[9].
There might be other issues, but the ones mentioned above are the ones I spotted at a first glance.
Hi I am working on a class for a weather station that asks a user to input variables and it passes the hours to an array: calculating the values for average, Highs and lows. I got it to work but want to make the array[elements] private. Is it possible to do this?
Here is my code so far. Thank you in advance for any help.
Brian
#include <iostream>
#include <iomanip>
using namespace std;
class WeatherStation
{
public:
WeatherStation();
void GetATemperatures(int[], int);
void DisplayATemperatures( int[], int);
void arrayCalcs(int[], int);
private:
static const int aTemps = 24;
static const int atemps[aTemps];
};
WeatherStation::WeatherStation()
{
int atemps[aTemps];
}
void WeatherStation::GetATemperatures(int atemps[], int aTemps)
{
for (int i = 0; i < aTemps; i++ )
{
cout << "Please enter the temperature for " << i << ":00 ";
while(true)
{
cin >> atemps[i];
if(atemps[i] >= -50 && atemps[i] <= 130)
{
break;
} else {
cout << "This temperature is not valid\n";
cout << "Please enter a temperature between -50 and 130 degrees F \n";
cout << "Please enter a new temperature: ";
}
}
}
}
void WeatherStation::DisplayATemperatures( int atemps[], int aTemps)
{
cout << setw (5) << "Hour" << setw(24)<< "Temperature \n";
cout << "\n";
for (int k = 0; k < aTemps; k++)
{
cout << setw (3) << k << ":00" << setw (16) << atemps[k]<<endl;
}
cout <<"\n";
}
void WeatherStation::arrayCalcs(int atemps[], int aTemps)
{
int sumA = 0;
double average = 0.0;
int minA = atemps[0];
int maxA = atemps[0];
int lowest = 0;
int highest = 0;
//Sum of the AM temps
for (int kk = 0; kk < aTemps; kk++)
{
sumA = sumA + atemps[kk];
}
//calculation for average
average = sumA / aTemps;
//Figuring out the Min and Max AM temps
for (int MM = 0; MM < aTemps; MM++)
{
if(minA > atemps[MM])
{
minA = atemps[MM];
}
else if(maxA < atemps[MM])
{
maxA = atemps[MM];
}
lowest = minA;
highest = maxA;
}
//Display of the Calculation results
cout << "This is the average of todays temperatures: " << average <<endl;
cout <<endl;
cout << "Todays High temperature is: " << highest <<endl;
cout <<endl;
cout << "Todays Low temperature is: " << lowest <<endl;
}
int main()
{
cout <<"Welcome to the weather station.\n";
cout <<"Please enter Ferenheit temperatures for calculations: \n";
WeatherStation alpha;
alpha.GetATemperatures(atemps, aTemps);
alpha.DisplayATemperatures(temps, Temps);
alpha.arrayCalcs(temps,Temps);
cout << "\n";
system("pause");
return 0;
}
1) Is the array atemps[]? If so, it's already private... what's the problem?
2) Why is your array class member static? Don't do that without damned good reason (and as this appears to be a homework assignment, I'm almost certain you don't have a damned good reason).
3) Your constructor has a useless line of code in it -- and that's the only line in the function.
4) Your professor will not accept you naming variables atemps and aTemps -- and if they do overlook it, I would be very concerned for the quality of education you're receiving. It's not that the variable names themselves are a big issue, but rather that you're naming them so similarly, as this is a recipe for a maintenance nightmare if it were to happen in real code.
Edit -- based on our comment-chat, here is my suggestion. I have not tried to compile this and I don't claim this is the best (or even a suggested) way to write your program... my suggestion is limited to leaving the data within your object (in a way that has room for growth beyond this question / discussion).
#include <iostream>
#include <iomanip>
using namespace std;
class WeatherStation
{
public:
WeatherStation();
void GetATemperatures();
void DisplayATemperatures();
void arrayCalcs();
private:
static const int aTemps = 24;
int atemps[aTemps];
};
WeatherStation::WeatherStation()
{
}
void WeatherStation::GetATemperatures()
{
for (int i = 0; i < aTemps; i++ )
{
cout << "Please enter the temperature for " << i << ":00 ";
while(true)
{
cin >> atemps[i];
if(atemps[i] >= -50 && atemps[i] <= 130)
{
break;
} else {
cout << "This temperature is not valid\n";
cout << "Please enter a temperature between -50 and 130 degrees F \n";
cout << "Please enter a new temperature: ";
}
}
}
}
void WeatherStation::DisplayATemperatures()
{
cout << setw (5) << "Hour" << setw(24)<< "Temperature \n";
cout << "\n";
for (int k = 0; k < aTemps; k++)
{
cout << setw (3) << k << ":00" << setw (16) << atemps[k]<<endl;
}
cout <<"\n";
}
void WeatherStation::arrayCalcs()
{
int sumA = 0;
double average = 0.0;
int minA = atemps[0];
int maxA = atemps[0];
int lowest = 0;
int highest = 0;
//Sum of the AM temps
for (int kk = 0; kk < aTemps; kk++)
{
sumA = sumA + atemps[kk];
}
//calculation for average
average = sumA / aTemps;
//Figuring out the Min and Max AM temps
for (int MM = 0; MM < aTemps; MM++)
{
if(minA > atemps[MM])
{
minA = atemps[MM];
}
else if(maxA < atemps[MM])
{
maxA = atemps[MM];
}
lowest = minA;
highest = maxA;
}
//Display of the Calculation results
cout << "This is the average of todays temperatures: " << average <<endl;
cout <<endl;
cout << "Todays High temperature is: " << highest <<endl;
cout <<endl;
cout << "Todays Low temperature is: " << lowest <<endl;
}
int main()
{
cout <<"Welcome to the weather station.\n";
cout <<"Please enter Ferenheit temperatures for calculations: \n";
WeatherStation alpha;
alpha.GetATemperatures();
alpha.DisplayATemperatures();
alpha.arrayCalcs();
cout << "\n";
system("pause");
return 0;
}