5月1scanf()使用笔记
1 #include<stdio.h>
2
3 int max_int(int ,int ,int);
4
5 int main(void){
6
7 int a,b,c;
8 scanf("%d %d %d",&a,&b,&c);
9 printf("%d ,%d, %d 三个数的最大值为:%d\n",a,b,c,max_int (a,b,c));
10 return 0;
11 }
12
13 int max_int(int a,int b,int c){
14 a=a>b?:b;
15 a=a>c?:c;
16 return a;
17 }
scanf("%d %d %d",&a,&b,&c);//1
scanf("%d %d %d ",&a,&b,&c);//2
这两句代码的区别,今天学C时写代码遇到的问题第一遍写的时候用是2这个后面多了个空格的
[xttcqw@localhost code]$ b511
12 34 56 6
12 ,34, 56 三个数的最大值为:56
[xttcqw@localhost code]$
代码执行的时候就必须输入第四个数,代码才会运行下去
[xttcqw@localhost code]$ b511
12 43 98
12 ,43, 98 三个数的最大值为:98
[xttcqw@localhost code]$
修改后就正常了,三个数回车就可以了
scanf()读取输入数据;
#include<stdio.h>
int main(void){
char ch;
scanf("%c",&ch);
while(ch !='g'){
printf("%c",ch);
scanf("%c",&ch);
}
return 0;
}
用户输入Go west ,young man!回车后程序输出
Go west ,young man!
Go west ,youn[xttcqw@localhost code]$
在这里作为一个初学者就好奇用户输入了一次多个字符scanf("%c",&ch);
却能连续的读取前面用户输入的字符串的字符,在这里自己就做个程序检验下
#include<stdio.h>
int main(void){
char ch,ch1,ch2,ch3;//定义多个char变量多次依次读取
scanf("%c",&ch);
/*while(ch !='g'){
printf("%c",ch);
scanf("%c",&ch);
}*/
printf("%c\t",ch);
scanf("%c",&ch1);
printf("%c\t",ch1);
scanf("%c",&ch2);
printf("%c\t",ch2);
scanf("%c",&ch3);
printf("%c\t",ch3);
return 0;
}
[xttcqw@localhost code]$ b24
Go west ,young man!
G o w
程序运行结果scanf()依次读取了三个字符(跳过空格)G o w
因此可以理解为scanf()的连续使用为顺序读取上次用户输入的数据
下面我们在做个试验,用户输入两个字符,看看ch3能否有什么结果?
[xttcqw@localhost code]$ b24
go
g o
程序读取了两个字符后停了下来等待用户输入
[xttcqw@localhost code]$ b24
go
g o
b
b [xttcqw@localhost code]$
输入b后屏幕打印出b后程序完成使命后结束。
写代码是学习探索代码用途的好方法,写一遍比看几遍的用处更大。