سؤال

In Objective-C (or C), if I do

CGFloat distance = 215;
CGFloat velocity = 20;
NSTimeInterval time = distance / velocity;

is that correct? Or, should I cast either distance or velocity to NSTimeInterval?

Note, in iOS 7.0:

#if defined(__LP64__) && __LP64__
# define CGFLOAT_TYPE double
#else
# define CGFLOAT_TYPE float
#endif

typedef CGFLOAT_TYPE CGFloat;

typedef double NSTimeInterval;
هل كانت مفيدة؟

المحلول

This code will divide the two values and produce the mathematical quotient rounded to a CGFloat. Then it will convert that CGFloat to an NSTimeInterval (which does not change the value) and store it in time.

If the CGFloat result is accurate enough for your needs (even when it is float), then the code is fine. If it is not, then you should convert one of the operands to NSTimeInterval, which will result in the quotient being rounded to an NSTimeInterval instead of a CGFloat.

If an NSTimeInterval result is not accurate enough, then you need alternative code.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top