1

I have a problem with my Objective-C code. I would like to have an if statement in a formula saying that the condition is checked just as if a float is equal to one of the other 5 I have defined. But shorter and simpler than:

 if (float1 == float5 || float1 == float2 || float1 == float3 || float1 == float11)
 {
        //something to do
 }

Thank you very much for your answers.

user2187565
  • 37
  • 1
  • 5
  • 2
    Never compare float with an int value – Anoop Vaidya Mar 20 '13 at 12:40
  • 1
    This is completely unrelated to Xcode. What you're having problems is C (at most Objective-C), the IDE has nothing to do with your code **at all.** –  Mar 20 '13 at 12:45
  • @AnoopVaidya: Never say never, unless you actually understand what you're saying. Uncritically parroting that "common wisdom" helps no one. – Stephen Canon Mar 20 '13 at 13:16
  • Careful. You can use integers in floating-point comparisons because C normally performs a widening conversion automatically (Kerningham, Ritchie, The C programming language, p. 42). – Thorsten S. Mar 20 '13 at 13:36

1 Answers1

0

Assuming that you can guarantee that the float is an integer, either by definition or applying roundf(), floorf(), ceilf(), this is a possible solution:

const NSUInteger LENGTH = 7;
float myNumbersToCheck[LENGTH] = {1,13,6,8,99,126,459674598};
for (NSUInteger index = 0; index < LENGTH; index++) {
  if (float1 == myNumbersToCheck[index]) {
     // do something
     break;
  }
}
Thorsten S.
  • 4,144
  • 27
  • 41
  • Thank you but I've modified my ask. I want to compare float and float – user2187565 Mar 20 '13 at 13:19
  • What exactly is the problem with float myNumbersToCheck[LENGTH] = {float1,float2,float3,float11} ?! – Thorsten S. Mar 20 '13 at 13:23
  • 1
    @user2187565: You can simply fill in the `myNumbersToCheck` array with the values you want to compare to. However, to compare to a few arbitrary values, there is not much reason not to simply write out the comparisons. Nothing else will be significantly clearer or more efficient. If there were more numbers or were a pattern or certain restrictions on the numbers, there might be other solutions such as using a binary search or looking up the result in an array of (effectively) Boolean values. But for just a few numbers, do not over-think this; just write the code. – Eric Postpischil Mar 20 '13 at 13:23
  • @Eric: True, I think the breaking point is more than 5 numbers. After that, I am aware that I am not "seeing" the equation fully anymore. If then an error like using && instead of || happens, I can seek for it a long time. Painful experience.... – Thorsten S. Mar 20 '13 at 13:31