Do I need to use decimals when using floats? Do I need the suffix "f"?

I have seen several examples in books and on the Internet where they sometimes use decimal places when declaring float values, even if they are integers, and sometimes the suffix "f". It's necessary?

For instance:

[UIColor colorWithRed:0.8 green:0.914 blue:0.9 alpha:1.00];

How is this different from:

[UIColor colorWithRed:0.8f green:0.914f blue:0.9f alpha:1.00f];

Does the final "f" mean anything special?

Getting rid of trailing zeros for an alpha value also works, so it becomes:

[UIColor colorWithRed:0.8 green:0.914 blue:0.9 alpha:1];

So, are there decimal zeros to remind ourselves and others that the value is a float?

Only one of those things that puzzled me, so any clarification is welcome :)

+3
source share
3 answers

, . TomTom .

, double const float (, , )... , , ... . , , .

, float, double, double ( f), float, . , .

: https://gist.github.com/1880400

iPad 1 (Release f):

------------ 10000000 total loops
timeWithDoubles: 1.33593 sec
timeWithFloats: 0.80924 sec
Float speed up: 1.65x
Difference in calculation: -0.000038

:

int main (int argc, const char * argv[]) {
  for (unsigned int magnitude = 100; magnitude < INT_MAX; magnitude *= 10) {
    runTest(magnitude);
  }
  return 0;
}

void runTest(int numIterations) {
  NSTimeInterval startTime = CFAbsoluteTimeGetCurrent();
  float d = 1.2f;
  for (int i = 0; i < numIterations; i++) {
    d += 1.8368383;
    d *= 0.976;
  }
  NSTimeInterval timeWithDoubles = CFAbsoluteTimeGetCurrent() - startTime;

  startTime = CFAbsoluteTimeGetCurrent();
  float f = 1.2f;
  for (int i = 0; i < numIterations; i++) {
    f += 1.8368383f;
    f *= 0.976f;
  }
  NSTimeInterval timeWithFloats = CFAbsoluteTimeGetCurrent() - startTime;
  printf("\n------------ %d total loops\n", numIterations);
  printf("timeWithDoubles: %2.5f sec\n", timeWithDoubles);
  printf("timeWithFloats: %2.5f sec\n", timeWithFloats);
  printf("Float speed up: %2.2fx\n", timeWithDoubles / timeWithFloats);
  printf("Difference in calculation: %f\n", d - f);
}
+2

. 1.0f float ( , ). , , , . , .

+5

f: float.

f + "." - .

.

8f 8 .

8.0 - 8 .

8 8 .

8.0f - 8 .

Basically, "f" can be a style - to make sure it's a float, not a double.

-2
source

Source: https://habr.com/ru/post/1735950/


All Articles