scanf(格式控制,地址列表)
提示
在vs新版本编译器中直接使用scanf函数会提示警告,无法操作运行,并会推荐使用 scanf_s()
,
可以在文件头部前面添加一行 #pragma warning(disable:4996) ,继续使用scanf函数。
它们的区别:
例如:name[5]
与printf函数中的格式声明相似,以%开始,以一个格式字符结束,中间可以插入附加的字符
scanf("a=%f,b=%d,c=%s",&a,&b,&c)
#include <stdio.h>
void main(){
int a, b, c;
scanf_s("%d%d%d", &a, &b, &c);
printf("%d,%d,%d\n", a, b, c);
}
1.scanf函数中没有精度控制。
scanf(%7.2f",&a);
scanf(%f",&a);
2.scanf涵数中要求给出变量地址,而不是变量名
scanf("%d",a);
scanf("%d",&a);
3.若格式控制串中没有非格式字符作输入数据之间的间隔,则可用空格,TAB或回车作间隔,如果有非格式字符,则在输入时,在对应位置上要输入这些字符。
4.在输入字符数据时,若格式控制串中无非格式字符,则认为所有输入的字符均为有效字符。
5.如果%后有一个“ * ”附加说明符,表示跳过它指定的列数。
例子:
输入格式符用逗号分隔,在控制台输入时就也要输入逗号进行分隔
#include <stdio.h>
void main(){
int a, b, c;
scanf_s("%d,%d,%d", &a, &b, &c);
printf("%d,%d,%d\n", a, b, c);
}
输入字符数据,空格会认为是有效字符,这里就不能使用scanf_s实现了,因为scanf_s检查输入边界的机制,导致程序报错,无法继续执行
#include <stdio.h>
#pragma warning(disable:4996)
void main(){
char a, b, c;
scanf("%c%c%c", &a,&b,&c);
printf("%c,%c,%c\n",a,b,c);
}
%后有一个“ * ”附加说明符
#include <stdio.h>
void main(){
int a, b;
scanf_s("%2d %*3d %d", &a, &b);
printf("%d,%d\n", a, b);
}
输入三角形的三边长,求三角形面积。设输入的三边长a、b、c能构成三角形。
#include <stdio.h>
#include <math.h>
void main(){
float a, b, c, p, area;
scanf_s("%f %f %f", &a, &b, &c);
p = (a + b + c) / 2;
area = sqrt(p *(p - a)*(p - b)*(p - c));
printf("a=%.2f b=%.2f c=%.2f p=%.2f area=%.2f\n",a,b,c,p,area);
}
从键盘输入一个大写字母,要求改用小写字母输出。
#include <stdio.h>
void main()
{
char c1, c2;
c1 = getchar();
c2 = c1 + 32;
printf("%c\n",c2);
}
求ax²tbx+c=0方程的根。a,b,c由键盘输入,设b²-4ac>0。
求根公式:
x1 = p + q; x2 = p - q
#include <stdio.h>
#include <math.h>
void main()
{
float a,b,c,x1,x2,p,q;
scanf_s("%f %f %f", &a, &b, &c);
p = -b / (2 * a);
q = sqrt(b * b - 4 * (a*c)) / (2*a);
x1 = p + q;
x2 = p - q;
printf("x1=%.2f,x2=%.2f\n",x1,x2);
}