对于一个printf语句混乱 [英] Confusion regarding a printf statement

查看:120
本文介绍了对于一个printf语句混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我运行此code

So I was running this code

#include<stdio.h>
int add(int x, int y)
{
return printf("%*c%*c",x ,' ',y,' ');

}
int main()
{
printf("Sum = %d", add(3,4));
return 0;
}

和似乎无法理解如何做下面的语句作品

And can't seem to understand how does the following statement works

return printf("%*c%*c",x ,' ',y,' ');  

于是,我试着写一个简单的code

So I tried writing a simple code

int x=3;
printf("%*c",x);

和我有一个奇怪的特殊字符(之前它的一些空格)作为输出

and I got a weird special character (some spaces before it) as output

printf("%*c",x,' ');

我越来越没有输出。我不知道发生了什么事?请帮忙。谢谢你。

I am getting no output. I have no idea what is happening? Please Help. Thank you.

推荐答案

这code

int x=3;
printf("%*c",x,'a');

利用,可以为每个输入参数的printf 设置为的最小字符宽度。

makes use of the minimum character width that can be set for each input parameter to printf.

什么上面所做的是打印出来的 A 字符,但指定最小宽度为 X 字符 - 所以输出将是 A 字符$ p 2位pceded $

What the above does is print out the a character, but specifies that the minimum width will be x characters - so the output will be the a character preceded by 2 spaces.

* 符告诉的printf ,输出字符串的部分的宽度从这个输入参数形成会为 X ,其中 X 必须作为附加参数传递字符的最小宽度之前以变量要被打印。特宽幅(如果需要)从空格输出的 以打印变量之前形成的。在这种情况下的宽度为3等的输出串(不包括其中仅仅存在引号来说明空格)的

The * specifier tells printf that the width of the part of the output string formed from this input parameter will be x characters minimum width where x must be passed as additional argument prior to the variable that is to be printed. The extra width (if required) is formed from blank spaces output before the variable to be printed. In this case the width is 3 and so the output string is (excluding the quotes which are just there to illustrate the spaces)

"  a" 

通过您的code此处

printf("%*c",x);

您已经通过了长度值,但忘了其实传递您想打印的变量。

you have passed the length value, but forgotten to actually pass the variable that you want printed.

所以这code

return printf("%*c%*c",x ,' ',y,' ');

基本上是说打印空格字符但与 X 字符的最小宽度(与codeX = 3),然后用打印的空格字符 Y的最低字符(在codeY = 4)。

is basically saying to print the space character but with a minimum width of x characters (with your code x = 3), then print the space character with a minimum of y characters (in your code y = 4).

其结果是,你打印出7空格字符。这个长度中的printf 的返回值(因此你的添加功能)通过输出

The result is that you are printing out 7 blank space characters. This length is the return value of printf (and hence your add function) which is confirmed by the output of

Sum = 7

的printf 的main()

如果你改变code到

return printf("%*c%*c",x ,'a',y,'b');

你会看到(不包括明显引号)字符串

you would see the string (obviously excluding the quotes)

"  a    b" 

印刷这将使正在发生的事情更加清楚。

printed which would make what is happening more clear.

这篇关于对于一个printf语句混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆