1

In Objective-C, is it a clean/safe approach to type cast let's say, a floating-point number to an integer with just assigning the floating-point variable to the int variable, and with the format specifier %i in NSLog call?

The proper way to do this is declaring the type cast like this:

int x; 
float y;

y = 7.43;

x = (int) y; //type cast (int)

NSLog(@"The value of x is %i", x);

Output:

The value of x is 7

This type-casting method would be the ideal approach, but I tried to just assign the floating-point variable into the int variable and it works the same, is there a difference?

This is the other method without the (type-cast):

int x;
float y;

y = 7.43;

x = y; // no (int) casting for variable 'y' here

NSLog(@"The value of x is %i", x);

Output:

The value of x is 7

As you can see, is the same result, what's the difference? both methods are good? which is cleaner?

4

1 回答 1

2

您不需要显式强制转换,但它不会造成伤害,它会使您的代码更具可读性。

我相信这是安全的,主要是因为最大浮点数比可能的 int 小得多,所以应该没有数据丢失。

确保您的意图是截断浮点值的小数部分而不是四舍五入。

于 2013-11-03T19:31:37.307 回答