你真的理解“她们”吗?

1.printf()

2.scanf()

1.printf()

printf函数也是有返回值的。

Return Value

Each of these functions returns the number of characters printed, or a negative value if an error occurs.

返回所打印字符的数,如果错误返回负值.

来个小题目:

KiKi写了一个输出“Hello world!”的程序,BoBo老师告诉他printf函数有返回值,你能帮他写个程序输出printf(“Hello world!”)的返回值吗?

读者可以自行做一下:

看作者的表演:

#include <stdio.h>
int main()
{
	printf("n%d", printf("Hello world!"));
	return 0;
}

小伙伴们,你们作对了吗? 

2.scanf()

scanf()库函数为读入函数,从键盘上读入,读入时先储存到一个名为缓冲区的储存区域,遇到'n'(即键盘上的Enter回车键)停止读入,下面就开始sacnf从缓冲区进行数据的读取,在遇到空格和非打印字符时停止读入,剩下的数据仍在缓冲区中储存着,等待着下一次的读取。

看下面这个题目:

描述

输入一个学生各5科成绩,输出该学生各5科成绩及总分。

输入描述:

一行,输入该学生各5科成绩(浮点数表示,范围0.0~100.0),用空格分隔。

输出描述:

一行,按照输入顺序每行输出一个学生的5科成绩及总分(小数点保留1位),用空格分隔。先看傻傻是我是怎么用数组做的:

 看下面的代码:

#include <stdio.h>
int main()
{
	float cj[5];
	float sum = 0;
	int n;
	for (n = 0; n < 5; n++)
	{
		scanf("%f", &cj[n]);
		sum += cj[n];
	}
	for (n = 0; n < 5; n++)
	{
		printf("%.1f ", cj[n]);
	}
	printf("%.1f", sum);
	return 0;
}

用我们c语言老师说的话讲:就这你居然用数组做,直接0分。

 其实是没有必要的:

#include <stdio.h>
int main()
{
	float cj;
	float sum = 0;
	int n;
	for (n = 0; n < 5; n++)
	{
		scanf("%f", &cj);
		sum += cj;
		printf("%.1f ", cj);
	}
	printf("%.1f", sum);
	return 0;
}

那我为什么还这样做呢?那就是没有明白scanf()函数的用法,一直是想着它只能读入一个。

其次scanf库函数是有返回值的:

下面是我在MSDN上截取的片段:

Return Value

Both scanf and wscanf return the number of fields successfully converted and assigned; the return value does not include fields that were read but not assigned. A return value of 0 indicates that no fields were assigned. The return value is EOF for an error or if the end-of-file character or the end-of-string character is encountered in the first attempt to read a character.

大概是什么意思呢?scanf返回成功读取的项数。如果没有读取任何项,且需要用户读取一个数字而却输入一个非数值字符,则返回0。遇到文件结尾时,返回EOF。

EOF的值是多少呢?我们转到定义:发现是-1

 

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
 

)">
下一篇>>