Вопрос

I tried to calculate 4/3 and store it into a float.

float answer = 4/3;

This only returns 1. Isn't objective-c able to calculate these kinds of fractions or do I have to do it any other way?

Это было полезно?

Решение

If numerator and denominator are both integers, then division will be integer. Use

float answer = 4/(float)3

Другие советы

4 and 3 are integers. So that division is an integer division, which evaluates to 1.

If you want a floating-point division, use (at least one) float literal.

float answer = 4f/3;

Your assignment contains an integer divide, which returns zero if the number you are dividing by is greater. You probably meant to do:

float p1 = (4.0f / 3.0f);

or

float p1 = ((float)4 / 3);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top