输入一个正整数n,然后读取n个正整数a1,a2,a3,……an,最后再读一个正整数m,统计a1,a2,a3……中有多少个整数小于m。用fopen和freopen输出。

题目:输入一个正整数n,然后读取n个正整数a1,a2,a3,……an,最后再读一个正整数m,统计a1,a2,a3……中有多少个整数小于m。

思路:如果是先输入m在输入n个数据,可以不使用数组,直接定义一个临时变量来保存输入的数据。如果是先输入的是数据,后输入m的值,就需要定义数组来保存输入数据。

一.fopen的用法:


#include<stdio.h>
#define M 1000
int main()
{
	FILE *fin,*fout;
	fin = fopen("stat.in","rb");
	fout = fopen("stat.out","wb");
	
		int n,m,t,count=0;
		int a[M];
		fscanf(fin,"%d",&n);
		
		for(int i=1;i<=n;i++)
		{
			fscanf(fin,"%d",&a[i]);
		}

		fscanf(fin,"%d",&m);

		for(int j=1;j<=n;j++)
		{
			if(m>a[j]) count++;

		}
		fprintf(fout,"%d",count);

		fclose(fin);
	    fclose(fout);

}

fopen的使用方法,先声明变量fin和fout。

FILE *fin,*fout;
fin = fopen("stat.in","rb");
fout = fopen("stat.out","wb");

把scanf改为fscanf,把printf改为fprintf,并且分别加上参数fin,fout。

fscanf(fin,"%d",&a[i]);
fprintf(fout,"%d",count);

最后定义:

  fclose(fin);
 fclose(fout);

如果要改为标准输入输出加上

fin=stdin;
fout=stdout;

并且删除 fclose(fin);fclose(fout);

二.freopen的用法:

#include<stdio.h>
#define M 1000
int main()
{
	freopen("stat.in","r",stdin);
	freopen("stat.out","w",stdout);

		int n,m,t,count=0;
		int a[M];
		scanf("%d",&n);

		for(int i=1;i<=n;i++)
		{
			scanf("%d",&a[i]);
		}

		scanf("%d",&m);

		for(int j=1;j<=n;j++)
		{
			if(m>a[j]) count++;

		}
		printf("%d",count);


}

只需加上

	    freopen("stat.in","r",stdin);
		freopen("stat.out","w",stdout);
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值