mthoutai

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

  1 头文件(stdio.h)

  •    scanf是stdio.h(standard input and output,基本输入输出)库中的函数,所以需要使用#include <stdio.h>将头文件包含进来,如过不包含,将提示scanf未定义。如下所示,我们将通过"//"将#include <stdio.h>注释掉,则提示错误如下(scanf was not declared...),因scanf在stdio.h中。):

        去掉对#include <stdio.h>的注释后,此时scanf被包含到当前程序中来,所以程序此时才运行正常,如下所示,没有报错。


2 scanf函数的一般形式

scanf(格式控制,地址列表)

 #include <stdio.h>
int main(void)
{
    int a,b,c,sum;
scanf("%d,%d,%d",&a,&b,&c);
    return 0; 
}

(1)%d,%d,%d:表示输入三个有符号的整数,用逗号隔开(其它符号分隔类似,如用空格隔开等);

  • 1,2,3
    --------------------------------
    Process exited after 8.165 seconds with return value 0
    请按任意键继续. . .

(2)&a,&b,&c(取地址符号):表示的是取a,b,c的地址,键盘输入数据写入对应地址。

#include 
int main(void)
{
    int a,b,c,sum;
    scanf("%d,%d,%d",&a,&b,&c);
    printf("%p,%p,%p",&a,&b,&c);
    return 0;
}
1,2,3
000000000062FE1C,000000000062FE18,000000000062FE14
--------------------------------
Process exited after 9.363 seconds with return value 0
请按任意键继续. . .

如上所示我们通过%p,输出a,b,c对应的地址(16进制),实际上,1,2,3对应的存储位置关系如下表:

1的存储地址2的存储地址3的存储地址
000000000062FE1C000000000062FE18000000000062FE14

从中我们可以看到1,2,3的地址相差4个字节(000000000062FE14与000000000062FE18相差4个字节,000000000062FE18与000000000062FE1C相差4个字节),这与C语言中int类型的长度定义一致(int 定义为4字节长度)。如果我们把a,b,c修改为double类型,则地址将相差8个字节,因double定义为8个字节。

#include 
int main(void)
{
    double a,b,c,sum;
    scanf("%f,%f,%f",&a,&b,&c);
    printf("%p,%p,%p",&a,&b,&c);
    return 0;
}
1,2,3
000000000062FE18,000000000062FE10,000000000062FE08
--------------------------------
Process exited after 3.591 seconds with return value 0
请按任意键继续. . .

16进制....FE18与...FE10相差8字节,这与实际一致。

(3)漏写“&”符号

  • #include 
    int main()
    {
    	int n;
    	scanf("%d",n);
    	printf("%d",n);
    }
  • 3
    --------------------------------
    Process exited after 8.583 seconds with return value 3221225477
    请按任意键继续. . .

未能执行后续输出操作。


#include <stdio.h> 
int main()
{
    int n;
    scanf("%d",&n);
    printf("%d",n);
}

加上"&"符号后,运行正常

3
3
--------------------------------
Process exited after 1.887 seconds with return value 0
请按任意键继续. . .


3 输出通过变量名(不需要&符号)

  • #include 
    int main(void)
    {
        int a,b,c,sum;
        scanf("%d,%d,%d",&a,&b,&c);
        printf("%d,%d,%d",a,b,c);
        return 0;
    }
  • 1,2,3
    1,2,3
    --------------------------------
    Process exited after 6.643 seconds with return value 0
    请按任意键继续. . .

在使用printf函数时,直接输出变量名,不需要使用地址。


posted on 2025-10-28 18:06  mthoutai  阅读(64)  评论(0)    收藏  举报