c的题目,小疑惑,大侠支招

来源:百度知道 编辑:UC知道 时间:2024/07/07 03:30:28
printf("求某一年龄段以上的职工总工资和平均工资。\n");
printf("回车是求全体职工平均工资,要求某一年龄段以上的输入y或Y\n");
getchar();//这个是干嘛用的啊,困惑
ch=getchar();
if(ch=='Y'||ch=='y')
{ printf("age:");
scanf("%d",&age);
}

据全国普通高等院校c语言程序设计教材(谭浩强 著)的书上解释如下:

第74页中:getchar函数(字符输入函数)的作用是从终端(或系统隐含指定的输入设备)输入一个字符。getchar()函数没有参数,其一般形式为
getchar()
函数的值就是从输入设备得到的字符。

函数名: getchar
功 能: 从stdin流中读字符
用 法: int getchar(void);
程序例:

#include <stdio.h>

int main(void)
{
int c;

/* Note that getchar reads from stdin and
is line buffered; this means it will
not return until you press ENTER. */

while ((c = getchar()) != '\n')
printf("%c", c);

return 0;
}

在这里就是判断你输入的是否是y或者Y
如果是Y或y,那么就显示age:然后使用scanf语句来获取age值

getchar();一般用做取字符的,有时也搭配输出使用,作用是运行时取回车键,直接可以查看程序结果*_*