printf("%d") 不显示我输入的内容 [英] printf("%d") doesn't display what I input

查看:68
本文介绍了printf("%d") 不显示我输入的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码:

printf("Enter a number : ");

scanf("%d", &number);

printf("%d is what I entered\n", &number);

我输入2,

预期输出:2 是我输入的

实际输出:2293324 是我输入的

这里有什么问题?

推荐答案

printf("%d is what I entered\n", &number);

是错误的,因为 %d(在 printf 中)需要 int 类型的参数,而不是 int*.这会调用 未定义行为,如 C11 标准草案 (n1570) 中所见(强调我的):

is wrong because %d(in the printf) expects an argument of type int, not int*. This invokes Undefined Behavior as seen in the draft (n1570) of the C11 standard (emphasis mine):

7.21.6.1 fprintf 函数

[...]

  1. 如果转换规范无效,则行为未定义.282) 如果任何参数不是相应转换规范的正确类型,则行为未定义.

使用修复它

printf("%d is what I entered\n", number);

<小时>

那么,为什么scanf需要在变量名前加上&?


Then, Why does scanf require & before the variable name?

请记住,当您使用 number 时,您传递的是变量 numbervalue,而当您使用 &number,你传递numberaddress(&是操作符的地址).

Keep in mind that when you use number, you pass the value of the variable number and when you use &number, you pass the address of number(& is the address-of operator).

所以,scanf 不需要知道number 的值.它需要它的地址(在本例中为 int*)以便将输入写入其中.

So, scanf does not need to know the value of number. It needs the address of it (an int* in this case) in order to write the input into it.

printf 不需要地址.它只需要知道要打印的值(在本例中为 int).这就是为什么您不在 printf 中的变量名称之前使用 &.

printf, on the other hand, does not require the address. It just needs to know the value (int, in this case) to be printed. This is why you don't use & before the variable name in printf.

这篇关于printf("%d") 不显示我输入的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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