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.
Related
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;
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.
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
This is a question i am working on:
Prompt the user to enter five numbers, being five people's weights. Store the numbers in a vector of doubles. Output the vector's numbers on one line, each number followed by one space.
Also output the total weight, by summing the vector's elements.
Also output the average of the vector's elements.
Also output the max vector element.
So far this is the code i have
#include <iostream>
#include <vector>
using namespace std;
int main() {
const int NEW_WEIGHT = 5;
vector<float> inputWeights(NEW_WEIGHT);
int i = 0;
float sumWeight = 0.0;
float AverageWeight = 1.0;
int maxWeight = 0;
int temp = 0;
for (i = 0; i < NEW_WEIGHT; i++){
cout << "Enter weight "<< i+1<< ": ";
cout << inputWeights[i]<< endl;
cin>> temp;
inputWeights.push_back (temp);
}
cout << "\nYou entered: ";
for (i =0; i < NEW_WEIGHT- 1; i++) {
cout << inputWeights.at(i)<< " ";
}
cout<< inputWeights.at(inputWeights.size() - 1) << endl;
for (i =0; i < NEW_WEIGHT; i++){
sumWeight += inputWeights.at(i);
}
cout <<"Total weight: "<< sumWeight<< endl;
AverageWeight = sumWeight / inputWeights.size();
cout <<"Average weight: "<< AverageWeight<< endl;
maxWeight= inputWeights.at(0);
for (i =0; i < NEW_WEIGHT- 1; i++){
if (inputWeights.at(i) > maxWeight){
maxWeight = inputWeights.at(i);
}
}
cout<< "Max weight: "<< maxWeight << endl;
return 0;
}
When i run this code, whatever inputs i use(for the cin>>(...)), i get all zero's as output and i do not know why. can i get some help please.
update
cleaned up the code a little by getting rid of the cout<< inputWeights[i]<< endl;
and by adjusting vector inputWeights; at the beginning of the program.But the outputs are still not exactly what they are supposed to be. Instead, only the first 2 inputted values make it as outputs. Any reason why? thanks
update this is the right or correct code. Hope it helps someone in future.
#include <iostream>
#include <vector>
using namespace std;
int main() {
const int NEW_WEIGHT = 5;
vector <float> inputWeights;
int i = 0;
float sumWeight = 0.0;
float AverageWeight = 1.0;
float maxWeight = 0.0;
float temp = 0.0;
for (i = 0; i < NEW_WEIGHT; i++){
cout << "Enter weight "<< i+1<< ": "<< endl;
cin>> temp;
inputWeights.push_back (temp);
}
cout << "\nYou entered: ";
for (i =0; i < NEW_WEIGHT- 1; i++){
cout << inputWeights.at(i)<< " ";
}
cout<< inputWeights.at(inputWeights.size() - 1) << endl;
for (i =0; i < NEW_WEIGHT; i++){
sumWeight += inputWeights.at(i);
}
cout <<"Total weight: "<< sumWeight<< endl;
AverageWeight = sumWeight / inputWeights.size();
cout <<"Average weight: "<< AverageWeight<< endl;
maxWeight= inputWeights.at(0);
for (i =0; i < NEW_WEIGHT- 1; i++){
if (inputWeights.at(i) > maxWeight){
maxWeight = inputWeights.at(i);
}
}
cout<< "Max weight: "<< maxWeight << endl;
return 0;
}
You're making a vector of size 5:
const int NEW_WEIGHT = 5;
vector<float> inputWeights(NEW_WEIGHT);
// == 0, 0, 0, 0, 0
Then, in your input loop, you're adding new values to the end:
inputWeights.push_back (42);
// == 0, 0, 0, 0, 0, 42
Then you're outputting the first five elements which were always zero.
You need to choose one thing or the other: either set the size of the vector at the start of the program, or grow the vector with push_back for as long as there's input. Both are valid options.
You can clean up your code and fix the problems by adopting modern C++ (as in, C++11 and later) idiom. You don't need to fill your code with for(int i = 0; i < something; i++) any more. There's a simpler way.
// Size fixed in advance:
vector<float> weights(NUM_WEIGHTS);
for (auto& weight : weights) { // note it's `auto&`
cout << "\nEnter next weight: ";
cin >> weight; // if it was plain `auto` you'd overwrite a copy of an element of `weight`
}
// Size decided by input:
vector<float> weights; // starts empty this time
cout << "Enter weights. Enter negative value to stop." << endl;
float in;
while (cin >> in) {
if(in < 0) {
break;
}
weights.push_back(in);
}
In either case, you can then play with the filled vector using another range-based for:
cout << "You entered: ";
for (const auto& weight : weights) {
cout << weight << " ";
}
You'll also need to remove the cout << inputWeights[i] << endl; line from your input loop if you resize the vector during input - as written you'd be reading elements which don't exist yet, and will probably get an array-index-out-of-bounds exception.
When you create define your inputWeights you are putting 5 items into it with default values.
vector<float> inputWeights(NEW_WEIGHT);
Change it to be just
vector<float> inputWeights;
And get rid of this line in your code or comment it out
cout << inputWeights[i]<< endl;
This is what you are looking for from the requirements of your program.
#include <vector>
#include <iostream>
int main() {
std::vector<double> weights;
double currentWeight = 0.0;
const unsigned numberOfWeights = 5;
std::cout << "Enter " << numberOfWeights << " weights" << std::endl;
unsigned i = 0;
for ( ; i < numberOfWeights; ++i ) {
std::cin >> currentWeight;
weights.push_back( currentWeight );
}
std::cout << "These are the weights that you entered: " << std::endl;
for ( i = 0; i < weights.size(); ++i ) {
std::cout << weights[i] << " ";
}
std::cout << std::endl;
double totalWeight = 0.0;
std::cout << "The total of all weights is: ";
for ( i = 0; i < weights.size(); ++i ) {
totalWeight += weights[i];
}
std::cout << totalWeight << std::endl;
std::cout << "The average of all the weights is: " << (totalWeight / numberOfWeights) << std::endl;
std::cout << "The max weight is: ";
double max = weights[0];
for ( i = 0; i < weights.size(); ++i ) {
if ( weights[i] > max ) {
max = weights[i];
}
}
std::cout << max << std::endl;
return 0;
}
The culprit to your problem for seeing all 0s as output is coming from these two lines of code:
const int NEW_WEIGHT = 5;
vector<float> inputWeights(NEW_WEIGHT);
which is the same as doing this:
vector<float> inputWeights{ 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };
you are then looping through up to 5 elements using NEW_WEIGHT when it would be easier to use inputWeights.size() when traversing through containers.
Edit - Condensed Version
#include <vector>
#include <iostream>
int main() {
std::vector<double> weights;
double currentWeight = 0.0;
const unsigned numberOfWeights = 5;
unsigned i = 0;
std::cout << "Enter " << numberOfWeights << " weights" << std::endl;
for ( ; i < numberOfWeights; ++i ) {
std::cin >> currentWeight;
weights.push_back( currentWeight );
}
double totalWeight = 0.0;
double max = weights[0];
std::cout << "These are the weights that you entered: " << std::endl;
for ( i = 0; i < weights.size(); ++i ) {
std::cout << weights[i] << " "; // Print Each Weight
totalWeight += weights[i]; // Sum The Weights
// Look For Max Weight
if ( weights[i] > max ) {
max = weights[i];
}
}
std::cout << std::endl;
std::cout << "The total of all weights is: " << totalWeight << std::endl;
std::cout << "The average of all the weights is: " << (totalWeight / numberOfWeights) << std::endl;
std::cout << "The max weight is: " << max << std::endl;
return 0;
}
I am having trouble with the following line of code:
double answer;
answer = num[count] / den[count]
cout << " Fraction" << count + 1 << " " << num[count]
<< " / " << den[count] << " = " << answer << endl;
How come my rendition of answer is not working? Am I overlooking something? I am using arrays and am getting the data from a separate text file. When I use the code above I get the numbers that are to be divided correctly but the answer is incorrect. It comes out to be a random number usually 0 or 1.
Here is my code:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstdlib>
using namespace std;
void read_data(int num[], int den[], int size);
void showValues(int num[],int den[], int size);
int main()
{
const int size1 = 12;
const int size2 = 12;
ifstream dataIn;
int num[12];
int den[12];
read_data(num,den,size1);
cout << "Here are the fractions: " << endl;
showValues(num,den,size1);
system("PAUSE");
return 0;
}
void read_data(int num[], int den[], int size)
{
ifstream dataIn;
dataIn.open("walrus.txt");
if( dataIn.fail() )
{
cout << "File does not exist." << endl;
exit(1);
}
int count;
for ( count = 0; count < size; count++ )
{
dataIn >> num[count];
}
for (count = 0; count < size; count++)
{
dataIn >> den[count];
}
dataIn.close();
}
void showValues(int num[],int den[], int size)
{
int count;
for (count = 0; count < size; count++)
{
if (den[count] == 0)
{
cout << " Fraction" << count + 1 << " "
<< num[count] << " /" << den[count]
<< " Is invalid" << endl;
}
else
{
double answer;
answer = num[count] / den[count];
cout << " Fraction" << count + 1 << " "
<< num[count] << " / " << den[count]
<< " = " << answer << endl;
}
}
}
#main ifstream dataIn;
You are not using this object
#function read_data :
int count;
for ( count = 0; count < size; count++ )
{
dataIn >> num[count];
}
for (count = 0; count < size; count++)
{
dataIn >> den[count];
}
Assuming ur file looks like :
1 2 23 32 44 // numerators
2 3 1 99 24 // den
The proper way to read is :
int count = 0;
while( count < size && dataIn >> num[count++] ) // numerators
;
count = 0;
while( count < size && dataIn >> den[count++] )
;
#function showValues :
try changing
double answer;
answer = num[count] / den[count];
cout << " Fraction" << count + 1 << " "
<< num[count] << " / " << den[count]
<< " = " << answer << endl;
to :
double answer = static_cast<double>(num[count]) / den[count];
cout << " Fraction" << count + 1 << " "
<< num[count] << " / " << den[count] << " = " << answer << endl;
In C and C++, if you do,
double answer = 10 / 3;
your answer will be 3. The reason is you have 2 integers and an integer division will take place. The resulting output is then implicitly converted into a double. So the steps are,
double answer = 10 / 3
double answer = 3
double answer = 3.0
To fix this, you tell the compiler that you want this to be treated as floating point division.
double answer = 10.0 / 3;
This works by,
double answer = 10.0 / 3
double answer = 10.0 / 3.0
double answer = 3.33333333...
The compiler will implicitly cast the 3 into a larger double type, 3.0.
So in your code, you have to convert integer division into floating point division by casting at least one of the division arguments into a double.
double foo = num[count] / den[count];
simply becomes
double foo = num[count] / static_cast<double>(den[count]);
Alternatively, if one or both of the arrays were of double type, you would not have this problem requiring casts.