math - Addition using printf in C -
this question has answer here:
- adding 2 numbers without using operators 2 answers
on net: using printf
add 2 numbers(without using operator) following:
main() { printf("summ = %d",add(10,20)) return 0; } int add(int x,int y) { return printf("%*d%*d",x,' ',y,' '); }
could please explain, how works:
return printf("%*d%*d",x,' ',y,' ');
note: fails when call "sum" following:
sum(1,1) or sum(3,-1)
there 2 central concepts here:
printf()
returns number of characters printed.- the
%*d
format specifier causesprintf()
read 2 integers arguments, , use first set field width used format second (as decimal number).
so in effect values being added used field widths, , printf()
returns sum.
i'm not sure actual d
formatting of space character, @ moment. looks weird, have gone empty string instead:
static int sum(unsigned int a, unsigned int b) { return printf("%*s%*s", a, "", b, ""); } int main(void) { unsigned int = 13, b = 6; int apb = sum(a, b); printf("%d + %d = %d?\n", a, b, apb); return 0; }
the above works , computes sum 19
.
Comments
Post a Comment