1

Given the char * variables name1 , name2 , and name3 , write a fragment of code that assigns the largest value to the variable max (assume all three have already been declared and have been assigned values).

I've tried and came up with this:

    if ((strcmp(name1,name2)>0)&&(strcmp(name1,name3)>0)){
max=name1;
}
else if ((strcmp(name2,name1)>0)&&(strcmp(name2,name3)>0)){
max=name2;
}
else if((strcmp(name3,name1)>0)&&(strcmp(name3,name2)>0)){
max=name3;
}
else if(strcmp(name3,name1)==0){
max=name1,name3;
}
else if (strcmp(name2,name1)==0){
max=name2,name1;
}
else if (strcmp(name2,name3)==0){
max=name2,name3;
}
else{
max=name1,name2,name3;
}

However, I get this error Your code is incorrect. You are not handling the situation                where two or more strings are equal.

Solved...

5
  • 1
    How do you get that error? Is it from a person?
    – WhirlWind
    Apr 21, 2010 at 3:54
  • The error message seems pretty clear. Look at your code carefully and consider what it does if all 3 strings are equal. (Among other cases) Apr 21, 2010 at 3:55
  • If all three strings are equal then there would be no largest value... What am I missing...
    – DomX23
    Apr 21, 2010 at 4:07
  • What is the largest value in the set (10, 10, 10)? The smallest value?
    – Fred
    Apr 21, 2010 at 4:19
  • Sounds like homework, I'll update the tag
    – Fuzz
    Apr 21, 2010 at 5:18

2 Answers 2

1

strcmp returns 0 when your strings are equal

I'll leave it for you to figure out why you aren't handling it.

Edit:

Bob and Alice are 10 years old.
What is the max age?

Hint: it's not undefined.... it's 10.

3
  • 100% agree with that statement!
    – Marlon
    Apr 21, 2010 at 3:56
  • Yeah and it returns a positive value if x>y in terms of strcmp(x,y).
    – DomX23
    Apr 21, 2010 at 4:03
  • 1
    Wow, I finally got it... I like how you guys make me solve the answer myself without providing code.
    – DomX23
    Apr 21, 2010 at 4:23
1

Watch out: strcmp does not do numeric comparison!

That is

strcmp("10","2")

returns a negative value, indicating that "2" is bigger than "10" which is almost certainly not what you want.

You probably want to convert the strings to numbers of some kind before comparing. Consider using sprintf or atoi or atof or strtod.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.