Objective c division of two ints

前端 未结 4 2049
臣服心动
臣服心动 2020-12-10 07:24

I\'m trying to produce a a float by dividing two ints in my program. Here is what I\'d expect:

1 / 120 = 0.00833

Here is the code I\'m using:

4条回答
  •  被撕碎了的回忆
    2020-12-10 08:13

    float a = 1/120;
    float b = 1.0/120;
    float c = 1.0/120.0;
    float d = 1.0f/120.0f;
    
    NSLog(@"Value of A:%f B:%f C:%f D:%f",a,b,c,d);
    
    Output: Value of A:0.000000 B:0.008333 C:0.008333 D:0.008333
    

    For float variable a : int / int yields integer which you are assigning to float and printing it so 0.0000000

    For float variable b: float / int yields float, assigning to float and printing it 0.008333

    For float variable c: float / float yields float, so 0.008333

    Last one is more precise float. Previous ones are of type double: all floating point values are stored as double data types unless the value is followed by an 'f' to specifically specify a float rather than as a double.

提交回复
热议问题