![Quote](https://cboard.cprogramming.com/images/misc/quote_icon.png)
Originally Posted by
dhuan
This is its objective:
It asks for the name and salary of a specific number of employees... Then it calculates and tells the user the average salary of the company, then it says who's the richest employee in the company;;;
I cant figure it out how to make it work
Code:
#include <iostream>
#include <string>
#define COMPANY_SIZE 2
using namespace std;
struct employee
{
string name;
float salary;
};
float getAverage (employee* e);
int getRichest (employee* e); // returns richest employee's id
int main()
{
employee emp[COMPANY_SIZE];
for(int x=0; x < COMPANY_SIZE; x++)
{
cout<<"Enter Employee's Name: ";
cin>>emp[x].name;
cout<<"Enter Employee's Salary: U$ ";
cin>>emp[x].salary;
cout<<endl;
}
cout<<"The Average Salary in this company is U$ "<<getAverage(emp)<<endl;
cout<<"The Richest Employee in this company is "<<emp[getRichest(emp)].name<<endl;
}
float getAverage(employee* e)
{
float accumulator=0;
for(int x=0; x <= COMPANY_SIZE; x++)
{
accumulator = accumulator + e[x].salary;
}
return (accumulator / COMPANY_SIZE);
}
int getRichest(employee* e)
{
float highest;
for(int x=0; x<=COMPANY_SIZE; x++)
{
highest = (x==0) ? x : highest;
highest = (e[x].salary > highest) ? x : highest;
}
return highest;
}
BTW, any adivice on making the code better is welcome!
Your "for" loop is incorrect. it should be:
Code:
for(int x=0; x < COMPANY_SIZE; x++)
because emp[2] does not exists. You only have emp[0] and emp[1].
in "getRichest", you don't need this in the for loop: "highest = (x==0) ? x : highest;" Just initialize "highest" to 0 outside the for loop, then use the for loop to update the value of highest. Otherwise, you'll do that operation at every single iteration; quite wasteful when you have a large array.
Furthermore, since you want to use "highest" as an index, you should declare it to be "int" instead of "float", and also that function need to return type "int".
In
Code:
accumulator = accumulator + e[x].salary;
you can just use C++ notation:
Code:
accumulator += e[x].salary;