How can I obtain which of this variables have the

2019-10-02 01:19发布

问题:

I have to know which of these variable have the highest value:

A=1
B=500
C=100
D=700
E=5
F=1000

Which is the easiest way to do this?

回答1:

You can pick one of them as the potential variable with the highest value. Then iterate through all the variables. At each iteration, see if that variable has a higher value than your candidate. If it does, replace your candidate. When you have iterated through all the variables, the potential candidate variable is the actual variable with the highest value.



回答2:

#include <stdio.h>
#include <limits.h>

#define max(x) max_value(x, #x)

typedef struct _var {
    const char *name;
    int value;
} Var;


Var max_value(int value, const char *name){
    static Var max = {NULL, INT_MIN};
    Var temp = { max.name, max.value };

    if(name != NULL){
        if( max.value < value){
            max.name = name;
            max.value = value;
            temp = max;
        }
    } else {
        temp = max;
        max.name = NULL;
        max.value = INT_MIN;
    }

    return temp;
}

int main(void){
    int A=1;
    int B=500;
    int C=100;
    int D=700;
    int E=5;
    int F=1000;
    Var v;

    v=max(A);
    v=max(B);
    v=max(C);
    v=max(D);
    v=max(E);
    v=max(F);
/*
    max(A);
    max(B);
    max(C);
    max(D);
    max(E);
    max(F);
    v = max_value(INT_MIN, NULL);//and reset
*/
    printf("max is %d of variable %s\n", v.value, v.name);//max is 1000 of variable F
    return 0;
}


标签: c max highest