How am I getting these outputs in C?

main()
{double=1/2.0-1/2;
printf("d=%.21f",d);
}
Output:0.50000000000000

shouldn't it be 0?

main()
{ int a=5;
a=printf("Good")
printf("%d",a);
}
Output:Good4

How come this?

main()
{printf("\nab");
printf("\bsi");
printf("rha");
}
Output:hai

How?
In the first snip, be wary of integer division! 1/2 = 0 when dealing with integers.

In the second snip... (for printf) "On success, the total number of characters written is returned." So you're printing the string "Good", then you're printing the return value of that printf which you stored in a.

In the third snip... not sure.
The third fragment makes sense if the last printf's string starts with \r rather than just r

\b = backspace
\r = carriage return (move to the start of the line)

And \n is new line, of course.

1
2
3
4
5
6
main()
{
    printf("\nab"); // print new line followed by ab
    printf("\bsi"); // backspace 1 char and output si
    printf("\rha"); // move to start of line and output ha
}


output after 1st printf


ab


After 2nd


asi


After 3rd


hai


Andy

PS Please use code tags in the future.

"How to use code tags"
http://www.cplusplus.com/articles/jEywvCM9/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <stdio.h>

int main()
{
    printf("======== START\n");

    printf("\nab");

    printf("\n");

    printf("\nab");
    printf("\bsi");

    printf("\n");

    printf("\nab");
    printf("\bsi");
    printf("\rha");

    printf("\n");

    printf("======== END\n");

    return 0;
}
Last edited on
Topic archived. No new replies allowed.