⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ep2_18.cpp

📁 这里有大量的c语言习题呢!真的是题海哦
💻 CPP
字号:
/*2.18 改造【例2.19】,将运行结果(100以内素数)存入文件。*/
#include<fstream>
#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;

const int n=100;
int main(){
	int a[n],i,j;
	char ch,b[256];
	ofstream ofile;
	ifstream ifile;
	for(i=0;i<n;i++) a[i]=1+i;			//用数组保存整数1-100
	a[0]=0;								//1不是素数,置0
	for(i=0;i<n;i++){
		if(a[i]==0)  continue;				//该数已经置0,判断下一个数
		for(j=i+1;j<n;j++) if(a[j]%a[i]==0) a[j]=0;	//是a[i]倍数的元素置0;
	}
	ofile.open("myfile2_18.txt");
	int count=0;
	ofile<<"1-"<<n<<"之间的素数:"<<endl;
	for(i=0;i<n;i++)						//输出所有素数
		if(a[i]!=0){
			ofile<<setw(6)<<a[i];
			count++;
			if(count%10==0)  ofile<<endl;	//每行10个数据
		}
	ofile.close();
	cout<<"是否要将文件输出?Y或N"<<endl;
	cin>>ch;
	if(ch=='y'||ch=='Y'){
		ifile.open("myfile2_18.txt");
		i=0;
		while(ifile.get(b[i])){//不可用>>,它不能读白字符,
			if(b[i]=='\n') break;
			i++;
		}
	b[i]='\0';
	cout<<b<<endl;
	count=0;
	while(1){
		ifile>>i;//由文件读入		
		cout<<setw(6)<<i;//屏幕显示
		count++;
		if(count%10==0)  cout<<endl;	//每行10个数
		if(ifile.eof()!=0) break;//这里最后一个数据后面可能没有回车,直接为文件结束
	}
	ifile.close();
	cout<<endl;
	}
	return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -