To find sum of two numbers without using any operator. Only use of printf() is allowed.

来源:互联网 发布:淘宝手机充值漏洞 编辑:程序博客网 时间:2024/04/30 06:08

    We can use printf() to find sum of two numbers as printf() returns the number of characters printed.

    The width field in printf() can be used to find the sum of two numbers. We can use ‘*’ which indicates the minimum width of output. For example, in the statement “printf(“%*d”, width, num);”, the specified ‘width’ is substituted in place of *, and ‘num’ is printed within the minimum width specified. If number of digits in ‘num’ is smaller than the specified ‘wodth’, the output is padded with blank spaces(右对齐). If number of digits are more, the output is printed as it is (not truncated).

solution:

intadd(intx,inty)
{
    returnprintf("%*c%*c",  x,' ',  y,' ');
}
 
intmain()
{
    printf("Sum = %d", add(3, 4));
    return0;
}

Output:

       Sum = 7 
注意:Sum前面还会输出7个空格,因为add函数里面还会输出。如果想不输出前面的空格,可以用'\r'代替' ','\r'是使光标移到一行的开头。
int add(int x, int y)
{
    return printf("%*c%*c",  x, '\r',  y, '\r');
}
 
int main()
{
    printf("Sum = %d", add(3, 4));
    return 0;
}

Output:

Sum = 7


0 0
原创粉丝点击