305 views
8 8 votes

What is the output of the following code?

#include <stdio.h>

int main() {
    float x = 5 / 2;
    printf("%.1f", x);
    printf(" ");
    float y = 5.0 / 2;
    printf("%.1f", y);
    return 0;
}
  1. $\verb|2.5 2.0|$
     
  2. $\verb|2.0 2.5|$ 
     
  3. $\verb|3.0 3.0|$ 
     
  4. Compilation error

2 Answers

1 1 vote

In the statement $\texttt{float x = 5 / 2;}$, both $\texttt{5}$ and $\texttt{2}$ are integers.

So, integer division is performed first.

Thus, $\texttt{5 / 2 = 2}$.

Then this integer value $\texttt{2}$ is stored in the float variable $\texttt{x}$, so $\texttt{x = 2.0}$.

Now, in the statement $\texttt{float y = 5.0 / 2;}$, $\texttt{5.0}$ is a floating-point value.

So, floating-point division is performed.

Thus, $\texttt{5.0 / 2 = 2.5}$.

Therefore, the output is $\texttt{2.0\ 2.5}$.

Answer: B. $\texttt{2.0\ 2.5}$

Answer:
Position:
Show:

Related questions

8 8 votes
2 2 answers
337
337 views
GO Classes asked Jun 2
337 views
What is the output of the following code?#include <stdio.h int main() { int a = 5, b = 2; float x = a / b + 0.5; printf("%.1f", x); return 0; }
6 6 votes
2 2 answers
398
398 views
GO Classes asked Jun 2
398 views
What is the output of the following code?#include <stdio.h int main() { int i, sum = 0; for (i = 1; i <= 6; i++) { if (i % 2 == 0) continue; sum = sum + i; if (sum 6) br...
14 14 votes
3 3 answers
455
455 views
GO Classes asked Jun 2
455 views
What is the output of the following code?#include <stdio.h int main() { int a = 0, b = 5, c = 10; int ans = a++ && ++b || c ; printf("%d %d %d %d", ans, a, b, c); return ...
8 8 votes
3 3 answers
523
523 views
GO Classes asked Jun 2
523 views
What is the output of the following code?#include <stdio.h int main() { int x = 5; printf("%d", x++); printf("%d", ++x); return 0; }$57$ $67$ Compilation error Undefined ...