Maulik
Maulik

Reputation: 19418

unexpected values from division

I am getting some unexpected value from following code :

- (void) test
{
int target = 0;  
int received = 0;

float result = (float)received/target;

NSLog(@"%.0f",result);
}

in console it prints " nan ". The target and received values may change. but when both are 0 than issue is created. I want to display result's value on label but it prints nan instead of float value.

what is wrong in code ?

Thanks...

Upvotes: 1

Views: 395

Answers (5)

Tobias Wärre
Tobias Wärre

Reputation: 803

You divide by zero, which is usually an illegal arithmetic operation, will in this case produce an exception in the FPU (due to IEEE 754, which handles floating point arithmetics in microprocessors) and the result will be NaN which means 'Not a Number'.

The variable 'target' has to have a value which is separated from zero or the division will never be executed right. In past times, division by zero was a sure way to get a process to crash.

To catch the Nan you can include math.h and use the function isnan() to decide to proceed with errorhandling or the regular flow.

Upvotes: 3

DLRdave
DLRdave

Reputation: 14250

One other note here that is not mentioned in the other answers yet.

The line...

float result = (float)received/target;

...first casts recevied to (float), then divides by the integer value target. I don't know about the rest of you folks out there, but I do not know what the compiler does with this. I'd have to look it up.

On the other hand, I do know what the compiler does when you divide an int by an int, or a float by a float, ... without looking it up.

So. For the sake of future readers of your code, I encourage you to re-state your line of code as either int-by-int or float-by-float division. If you mean float-by-float, then a line like this would be easier for future readers to understand:

float result = (float) received / (float) target;

Upvotes: 0

Nikolai Ruhe
Nikolai Ruhe

Reputation: 81848

IEEE 754 defines that the result of 0.0 / 0.0 is a (silent) NaN.

A positive float divided by zero yields positive infinity. A negative dividend returns negative infinity.

Upvotes: 6

ljkyser
ljkyser

Reputation: 1019

You can catch the value with the method

isnan()

It takes a double and returns a bool. You could modify your code like this to work:

- (void) test
{
    int target = 0;  
    int received = 0;

    float result = (float)received/target;

    if (isnan(result))
    {
        result = 0;
    }
    NSLog(@"%.0f",result);
}

Upvotes: 2

Krishnabhadra
Krishnabhadra

Reputation: 34265

If you devide by zero the result is said to be undefined for programming language, in maths it is called infinity..See this , this and this..And nan means NotANumber..

Upvotes: 0

Related Questions