Daksh Shah
Daksh Shah

Reputation: 3113

Cant figure out the way compiler does the calculation

Given is a C code, in which i am trying to figure out how the calculation order would go, well i thought it should be 3/2 first and then *5 or the other way round. But it gives an unexpected output of

5.000000

#include <stdio.h>

int main(void) {
    // your code goes here
    float a = 3/2*5;
    printf("%f", a);
    return 0;
}

Upvotes: 2

Views: 102

Answers (4)

Andy Stow Away
Andy Stow Away

Reputation: 647

The multiplication and division operator have equal precedence in evaluation. Since both operators are left to right associative, integer division (3/2) is performed first resulting in 1 and then followed by multiplication with 5. Readup on operator associativity in C language

http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence

Upvotes: 0

damienfrancois
damienfrancois

Reputation: 59090

The line

float a = 3/2*5;

computes a as the integer division of 3 by 2, which is 1, then multiplied by 5 and cast to float.

Replace it with

double a = 3.0/2.0*5;

or

float a = 3.0f/2.0f*5;

and you'll get 7.500000

Upvotes: 3

A.B.
A.B.

Reputation: 16630

It divides the integer 3 by integer 2, then multiplicates by integer 5, and then converts to a float.

Try float a = 3.f/2*5;

Upvotes: 1

Baldrick
Baldrick

Reputation: 11840

This is expected.

It calcuates 3/2 first (as integer), which is truncated down to 1. Then it multiplies by 5.

Try casting the numbers to (float) in your calculation - then you'll get the expected answer.

As suggested by damienfrancois, you can also get the compiler to treat them as floating point numbers as follows:

float a = 3.0/2.0*5;

In general, if you don't give any indication otherwise (such as the .0, or a cast), the compiler will treat numbers as an integer

Upvotes: 6

Related Questions