0

Iam new to C programming and i guess this question might look foolish but I have searched and i didn't get a satisfactory answer:

My question is does hierachy of execution of operators depend on whether the declared variables are integer or float, here is a scenario which I don't understand; this is the first case:

main()
{
int i=2,j=3,k;
k=i/j*j;
printf("%d",k);

and the output to that is 0 which i don't agree with; But when I change the variables to float as in below;

main()
{
float i=2,j=3,k;
k=i/j*j;
printf("%f",k);

The output to becomes 2.00000

why is this?

Main
  • 1
  • 1

4 Answers4

2

In the first code snippet, the subexpression i/j has integer operands so integer division is performed. This means that the result is also an integer and any fractional part is truncated.

In the second snippet, both operands have floating point type so floating point division is performed.

dbush
  • 205,898
  • 23
  • 218
  • 273
1

does hierachy of execution of operators depend on whether the declared variables are integer or float?

Hierarchy of execution as in order, no.

However, results very much depend on the types. Division involving two integers results in a truncated integer, so 2 / 3 is zero, not two thirds as you may expect.

Then, when you multiply that by two, you still have zero.

An example can be seen when calculating percentage of a ratio. Let's say 40 of the 60 students in a class are male. If you wanted to know the percentage of males, there's a vast difference between the two formulae below:

int males = 40;
int total = 60;

bad_pct  = males / total * 100;   // 40/60=0,     0*100=0.
good_pct = males * 100   / total; // 40*100=4000, 4000/60=66.
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
1

and the output to that is 0 which i don't agree with;

The program is always right, people (programmers) do mistakes.

The operation below is an integer division and 2 divided by 3 is 0. Integer division does not round to the closest integer value which causes your confusuin.

i/j == 2/3 == 0

0___________
  • 60,014
  • 4
  • 34
  • 74
0

The issue of integer math vs. floating point math has been dealt with well already, but when you use the term "hierarchy of operators," I think you're referring to operator precedence.

No, it does not change this. Operator precedence is the same for floating point and integer math operations.

Chris
  • 26,361
  • 5
  • 21
  • 42
  • The reason why i said this is beacause I thought that it begins by executing j*j then divides the answer by i which would result to zero, but thanks now I know. – Main Feb 01 '22 at 02:23