C++ 做题 Ⅵ

x33g5p2x  于2022-04-10 转载在 其他  
字(2.4k)|赞(0)|评价(0)|浏览(467)

1、字符位移子串问题
输入两行字符串s1、s2,判断s2是否是s1经过若干次循环位移后产生的母串的子串。
返回判断答案

例如:
AABCD
CDAA
返回:true
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int N=60; 
int main(){
	char s1[N],s2[N],a[N],t[N];
	cout<<"请输入字符串s1:";
	gets(s1);	//输入字符串 
	cout<<"请输入字符串s2:";
	gets(s2);	 
	if(strlen(s1)<strlen(s2)){ //把s1作为母串,s2为子串判断 
		strcpy(t,s1); //交换子母串 
		strcpy(s1,s2);
		strcpy(s2,t);
	}
	strcpy(a,s1); //把母串赋给a 
	cout<<"------------------------------"<<endl;
	cout<<"母串:"<<strcpy(a,s1)<<endl;
	if(strstr(strcat(s1,a),s2)==NULL) 
		cout<<s2<<"不是"<<a<<"的位移子串"; 
	else
		cout<<s2<<"是"<<a<<"的位移子串";
}

2、判断2-100有多少个素数

#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
int prime(int); //函数声明
int sum=0;
int main(){
	for(int i=2;i<=100;++i)
		prime(i); //函数调用
	cout<<endl<<sum<<endl; 
}

int prime(int a){ //函数定义
	int c;
	if(a==2) sum=1;
	int j=2;
	while(j<=sqrt(a) && a%j !=0) j++;
	if(a%j!=0){
		sum +=1;
		cout<<a<<" "; 
	}
}

3、递归求最大公约数

#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
int gcd(int,int);
int sum=0;
int main(){
	int m,n,r;
	cout<<"请输入m,n的值:";
	cin>>m>>n;
	r=gcd(m,n);
	cout<<"最大公约数是:"<<r<<endl;
} 

int gcd(int m,int n) {
	return n==0 ? m:gcd(n,m%n); 	
}

4、递归求1+2+3+…+n的和

#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
int result(int);
int sum=0;
int main(){
	int n,r;
	cout<<"请输入n的值:";
	cin>>n;
	r=result(n);
	cout<<"总数是:"<<r<<endl;
} 

int result(int n) {
	if (n==1) return 1; 
	else return result(n-1)+n;
}

5、标准读入文件

#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
int main(){
	freopen("in.txt","r",stdin);
	freopen("out.txt","w",stdout);
	int temp,sum=0;
	while(scanf("%d",&temp)==1) {
		sum +=temp;
	}
	printf("%d\n",sum);
	fclose(stdin);
	fclose(stdout);
	return 0;
}

用fopen方式

#include <cstdio>
#include <cmath>
using namespace std;
int main(){
	FILE *fin,*fout;
	fin=fopen("in.txt","rb");
	fout=fopen("out.txt","wb");
	int temp,sum=0;
	while(fscanf(fin,"%d",&temp)==1){
		sum+=temp;
	}
	fprintf(fout,"%d\n",sum);
	fclose(fin);
	fclose(fout);
	return 0;
}

相关文章