Get max value

Hi,

I have a line in my code which calculates the sum of all a's:

a_total += a

I would like to adapt the line such that I obtain the maximum, instead of the sum. So something like:

a_max max= a

Of course this does not work like this. What would be the smartest way to do this? Thank you!

Cheers, Chris
Last edited on
I don't know whether this is particularly smart...
a_max = (a>a_max) ? a : a_max;
Since you have multiple "a"s, let's assume it to be an array.


int largest = a[0];
for (int i = 1; i < a_size; i++)
{
    if (a[i] > largest)
        largest = a[i];
}


Now you have iterated overy every element of a, and you've found the largest value and stored it in largest.
Hi!

Thank you both very much! The first answer from Chervil compiles properly, but I suspect it to be wrong, since a_max returns a lower value compared to when calculating the average of all a's.

The second answer (Bourgond) looks like it should work, but I cannot compile it. I imagine this occurs because in my code "a" is declared as "double". Simply exchanging "int" with "double" does not work either, I get:

error: invalid types ‘double[int]’ for array subscript

I'll keep trying (absolute beginner). Thanks in any case!

Cheers, Chris
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
using namespace std;

int main()
{
   int max=0;
   for (auto& k: {9,5,4,3,90,-4,91,23,29,-39})
      max = (k > max ? k : max);
   
   cout << max << endl;
   return 0;
}


compile with -std=c++11
Last edited on
Maybe you could post your code? Seems like there's some confusion regarding 'a'.
If I have correctly understood you you need to find the maximum value among enetered numbers.

This is being done in two steps. At first you assign the first entered number to a_max.

a_max = a;

Then when a next number is entered you should compare it with the current value of a_max:

if ( a_max < a ) a_max = a;

Last edited on
Hi everyone,

Sorry for the silence, I got distracted. Yes, Vlad, your approach works! Thanks to everyone!

All the best,
Chris
Topic archived. No new replies allowed.