Adding two numbers without using operators

后端 未结 3 718
迷失自我
迷失自我 2020-12-04 01:49

I found this following code for addition of two numbers without using the + operator.

code to add 3 and 4:

printf(\"%d\",printf(\"%*c%*c         


        
相关标签:
3条回答
  • 2020-12-04 02:05

    printf("%*c", n, c) prints the character c, n times. So the code prints 3 spaces followed by 4 spaces, and printf returns the number of characters printed, which is obviously 3 + 4, completing the problem.

    0 讨论(0)
  • 2020-12-04 02:06

    I am adding this answer to specify the rules of the standard.

    Here this is utilizing the return value of printf. Respectively 3-1 spaces(' ') and then again space (as you specified) and 4-1 spaces and then again 1 space is being printed. And then the total number of characters written is returned. That is how the sum is being done.

    I just remember this rule

    printf("%*c",X,C) prints the char C in a field of size X
    

    All these behavior is explained in C11 Standard.

    From standard §7.21.6.1p4

    An optional minimum field width. If the converted value has fewer characters than the field width, it is padded with spaces (by default) on the left (or right, if the left adjustment flag, described later, has been given) to the field width. The field width takes the form of an asterisk * (described later) or a nonnegative decimal integer.

    And in the same section §7.21.6.1p5

    As noted above, a field width, or precision, or both, may be indicated by an asterisk. In this case, an int argument supplies the field width or precision

    At last §7.21.6.1.p14

    The fprintf function returns the number of characters transmitted, or a negative value if an output or encoding error occurred.


    To clear your idea this example will be good enough (I am using %d here so that you get the idea of the field).

    If x = 10 and y=2 then it will be

    printf("%*d%*d",  x, x,  y, y);
    

    More clearly

    | | | | | | | | |1|0| |2|
     1 2 3 4 5 6 7 8 9 10 \ \
                          11 12
    
    That's how 12 characters are printed.
    
    0 讨论(0)
  • 2020-12-04 02:18

    The inner printf outputs 3 then 4 spaces and returns the number of characters, which is 7, and the outer printf is printing that result.

    0 讨论(0)
提交回复
热议问题