With this function I'm finding the highest average, but after I find it I want to find the name that goes with the highest average. I'm pretty sure I need to use the index of the highest average but I don't know how to do it.

void findHighest(int numItems,string name[], double average[])
//loops through averages to find the highest average
{
	int highest= average[0];
	
	for (int i=0; i< numItems; i++)
	{
		if(average[i]>highest)
		highest = average[i]; //i thing there needs to be something here for the index
		
	}
	
	cout << "Best percentage: " << highest  << " %"<< " by " << name/* i get garbage here*/ << endl;
	cout << " " << endl;

here is the output
"Best percentage: 100 % by 0x7fff61192948"

Recommended Answers

All 5 Replies

The loop counter i IS the index value you want. Declare that loop counter above the loop so that its global to the whole function. Then on line 13 just use it name

line 4: change the data type of variable highest from int to double because array average is of type double.

void findHighest(int numItems,string name[], double average[])
//loops through averages to find the highest average
{
	double highest= average[0];
	int i;
	
	for (int i=0; i< numItems; i++)
	{
		if(average[i]>highest)
		highest = average[i];
		
	}
	
	cout << "Best percentage: " << highest  << " %"<< " by " << name[i] << endl;
	cout << " " << endl;
	
	
}

i get this error, (Run Command: line 1: 24048 Segmentation fault: 11 ./"$2")

You need a second variable to keep track of the i value when you find the highest.

I still don't understand. This was a project for a class, but that class is over and I turned it in as is. If someone could tell me what I am doing wrong that would be great . It's driving me crazy.

void findHighest(int numItems,string name[], double average[])
//loops through averages to find the highest average
{
	int index = 0;
        double highest = average[0];        	
	for (int i=1; i< numItems; i++)
	{
		if(average[i]>highest)
		    index = i;
		
	}
	
	cout << "Best percentage: " << highest  << " %"<< " by " << name[index] << endl;
	cout << " " << endl;
	
	
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.