C language/C++ exercises

C++ exercises

1. Calculate how many days there are in a month

Topic: Input the year and month from the keyboard and output the number of days in the month.
[Sample input] 2023 1

【Sample output】31

[Sample input] 2020 2

[Sample Output] 29
Tips: When the input month is February, it is necessary to determine whether the year is a leap year.
Conditions for judging a leap year: the year is a multiple of 4 and not a multiple of 100, or the year is a multiple of 400.

int main(){
    
    	
	int year,month,day=0;
	cout<<"请输入年份和月份,以空格分隔:";
	cin>>year>>month;
	switch(month){
    
    
		case 1:
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
		case 12:day=31;break;
		case 4:
		case 6:
		case 9:
		case 11:day=30;break;
		case 2:
			if(year%4==0&&year%100!=0||year%400==0){
    
    
				day=29;
			}else{
    
    
				day=28;
			}
			break;
		default:cout<<"月份输入有误。";
	}
	if(day!=0){
    
    
		cout<<year<<"年"<<month<<"月有"<<day<<"天";
	}
}

2. Output the prime numbers between 1-200.

Print all prime numbers between 1-200 on the console, separated by spaces.

Hint: Only 1 and the number itself is divisible by itself is a prime number.

int main(){
    
    
	bool flag; 
	for(int i=2;i<=200;i++){
    
    
		flag=false;
		for(int j=2;j<i;j++){
    
    
			if(i%j==0){
    
    
				flag=true;
				break;
			}
		}
		if(!flag){
    
    
			cout<<i<<" ";
		}
	} 
}

3. Calculate the sum of matrix edge elements

Input a matrix of integers and compute the sum of the elements lying on the edge of the matrix. The so-called elements on the edge of the matrix are the elements in the first row and the last row and the elements in the first column and the last column.

enter description

The first line is the number of rows m and the number of columns n (m<100, n<100) of the matrix respectively, and the two are separated by a space.
In the next m lines of data input, each line contains n integers, and the integers are separated by a space.

output description

Outputs the sum of the edge elements of the corresponding matrix.

Use case input 1

3 3
3 4 1
3 7 1
2 0 1

Use case output 1

15
#include<iostream>
using namespace std;

int main()
{
    
    
    int n,m;
    cin>>m>>n;
    int arr[m][n];
    for(int i=0;i<m;i++){
    
    
        for(int j=0;j<n;j++){
    
    
            cin>>arr[i][j];
        }
    }
	int sum=0;
    for(int i=0;i<m;i++){
    
    
        for(int j=0;j<n;j++){
    
    
            if(i==0||i==m-1){
    
    
                sum+=arr[i][j];
            }else if(j==0||j==n-1){
    
    
                sum+=arr[i][j];
            }
        }
    }
    cout<<sum;
}

4. Determine the number of digits

Write a function get_length(...) that calculates how many digits the input positive integer has.

enter description

A positive integer (no more than 10 digits).

output description

An integer representing the number of digits of the input positive integer

Use case input 1

123456

Use case output 1

6
#include<iostream>
using namespace std;
int get_length(int n);
int main()
{
    
    
	int n;
	cin>>n;
	cout<<get_length(n);
 } 

int get_length(int n){
    
    
	//正整数的位数最少也有1位,所以初始值赋值为1
    int i=1;
	while(n/10!=0){
    
    
		n/=10;
		i++;
	}	
	return i;
}

5. Integer reorganization

Given any positive integer, recombine it into a maximum value and a minimum value, and find the difference between the two numbers. For example: 3721, the maximum number that can be reconstructed is 7321, the minimum number is 1237, and the difference between the two numbers is 7321-1237=6084.

enter description

x (integer 1≤x≤100000)

output description

difference between maximum and minimum

Use case input 1

3721

Use case output 1

6084
#include<iostream>
using namespace std;

int X(int *a,int n){
    
    
	int i=0;
	while(n!=0){
    
    
		a[i]=n%10;
		n=n/10;
		i++;
	}
	//对数组元素升序排序 
	for(int k=0;k<i;k++){
    
    
		for(int j=0;j<k;j++){
    
    
			if(a[k]>a[j]){
    
    
				int t=a[k];
				a[k]=a[j];
				a[j]=t;
			}
		} 
	}
	//返回整数的位数 
	return i;
} 
int main()
{
    
    
	int n;
	cin>>n;
	int a[100]={
    
    };
	//统计输入数字的位数,并将所有数位上的数以升序存到数组a中 
	int count=X(a,n);
	int max=0,min=0;
	int x=1,y=1;
	//最小值则以数组元素从前往后结合,最大值则以数组元素从后往前结合 
	for(int i=0,j=count-1;i<count;i++,j--){
    
    
		//最小值从前往后遍历,最大值从后往前遍历 
		//从个位开始,依次用数位上的数字x1,x10,x100,...... 
		min+=a[i]*x;
		x*=10;
		max+=a[j]*y;
		y*=10;
	}
	cout<<max-min;
 } 

6. Hail conjecture

Hail conjecture : it first spread in the United States, soon spread to Europe, and later brought to Asia by a Japanese named Kakutani. In layman's terms, the content of the hail conjecture is as follows: any given natural number n, when n is an even number, divide it by 2, that is, it becomes n/2; when n is an odd number, it becomes 3n+1, ..., after a certain number of steps, you will always get 1.
In the above evolution process, a sequence of numbers will appear by arranging the numbers that appear each time.
The problem we have to solve now is: for a given n, find the position of the first occurrence of 1 in the sequence of numbers.

enter description

Enter a natural number n. The position of the first occurrence of 1 in the output sequence.

output description

The position of the first occurrence of 1 in the output sequence.

Use case input 1

6

Use case output 1

9
#include<iostream>
using namespace std;

int main()
{
    
    
	long long n;
	cin>>n;
	long long index=0;
	while(true){
    
    
		index++;
		if(n==1){
    
    
			cout<<index;
			break;
		}
		if(n%2==0){
    
    
			n=n/2;
		}else{
    
    
			n=3*n+1;
		}
		
	}
 } 

7. The size of the rectangle

There is a very tacky tradition in the rectangular family: whoever is older takes precedence. The "ratio size" rule is:

  1. Bigger ones are preferred
  2. When the areas are the same, the one with the longer perimeter takes precedence

Please sort the n rectangles according to the "ratio size" rule, and output the serial number of each rectangle. The serial number of the rectangle is 1~n, which is consistent with the input sequence of the rectangle.

enter description

In line 1, enter a positive integer less than 100, indicating the number of rectangles;
in the next n lines, enter the length and width of a rectangle (both positive integers) in each line, separated by a single space.

output description

Output the sequence numbers of n squares. Each rectangle occupies a row.

Use case input 1

5 
9 7
3 4
2 3
2 6
3 21

Use case output 1

5
1
4
2
3

code:

#include <bits/stdc++.h>
using namespace std;
struct stu{
    
    
	int a;
	int b;
	int c;
};
stu s[100];
bool cmp(stu x,stu y){
    
    
    if(x.a*x.b==y.a*y.b){
    
    
        return x.a+x.b>y.a+y.b;
    }else{
    
    
        return x.a*x.b>y.a*y.b;
    }
}

int main(){
    
    
    int num;
    cin>>num;
    for(int i=0;i<num;i++){
    
    
        cin>>s[i].a>>s[i].b;
        s[i].c = i+1;
    }
    sort(s,s+num,cmp);
    for(int i=0;i<num;i++){
    
    
        cout<<s[i].c<<endl;
    }
    return 0;
}

8. Sort by birthday

The child knows the birthday of each student in the CSP interest group, and wants to program to sort the group members in order of age from oldest to youngest. But Xiao Tong's programming level is very good, and he has been busy for a long time but he has not realized his idea. Please, as a little programming expert, help him complete the sorting.

enter description

There are n+1 lines in the input, the first line is the total number n of the CSP interest group; the
second line to the n+1 line are each person's name s, year of birth y, month m, day d.
1<n<100. Ensure that the year, month, and day actually exist, and the year is in the range of 1990~2022. Including 1990 and 2022.

output description

Output a total of n lines, that is, the names of n classmates whose birthdays are from oldest to youngest. (If there are two students with the same birthday, the student whose input is later will output first).

Use case input 1

3
Yangchu 1992 4 23
Qiujingya 1993 10 13
Luowen 1991 8 1

Use case output 1

Luowen
Yangchu
Qiujingya

code:

#include<bits/stdc++.h>
#include<string>
using namespace std;

struct stu{
    
    
    string name;
	int year;
    int month;
    int day;
};
stu s[100];
bool cmp(stu x,stu y){
    
    
    if(x.year!=y.year){
    
    
        return x.year<y.year;
    }else{
    
    
        if(x.month!=y.month){
    
    
        	return x.month<y.month;	
		}else{
    
    
			if(x.day!=y.day){
    
    
				return x.day<y.day;
			}else{
    
    
				return true;
			}
		}
	}
}

int main(){
    
    
    int num;
    cin>>num;
    for(int i=0;i<num;i++){
    
    
        cin>>s[i].name>>s[i].year>>s[i].month>>s[i].day;
    }
    sort(s,s+num,cmp);
    for(int i=0;i<num;i++){
    
    
        cout<<s[i].name<<endl;
    }
    return 0;
}

9. Candidates vote

There are 3 candidates: the surnames are "li", "zhang", and "sun". There are n voters, and each voter can only vote for one candidate. Input the votes of n voters, and output the vote results of the three candidates. Requirement: Use structures to solve problems.

enter description

Line 1 is a positive integer n. (10 ≤ n ≤ 100)
Line 2 is n strings. Each string is a candidate's last name.

output description

There are 3 lines in total. Output the votes of the three candidates in the order of "li", "zhang", and "sun", and the format is "last name: number of votes".

Use case input 1

10
zhang li sun sun li sun sun zhang zhang li

Use case output 1

li:3
zhang:3
sun:4
#include<bits/stdc++.h>
using namespace std;

struct stu{
    
    
    char name[100];
    int num;
};
stu s[100];

int main(){
    
    
	strcpy(s[0].name,"li");
	s[0].num=0;
	strcpy(s[1].name, "zhang");
	s[1].num=0;
	strcpy(s[2].name, "sun");
	s[2].num=0;
	
    int n;
    cin>>n;
    string c[100];
    int i=0;
    //将n个选民的投票情况保存到数组中 
	while(cin >> c[i])
    {
    
    
    	i++;
    	if(cin.get()=='\n'){
    
    
    		break;
		}		
	}
	//遍历数组,和结构体数据比较,如果姓氏相同,则候选人票数增加 
    for(i=0;i<n;i++){
    
    
	   for(int j=0;j<3;j++){
    
    
			if(s[j].name==c[i]){
    
    
				s[j].num+=1;
				break;
			}
	   }
    }
    for(i=0;i<3;i++){
    
    
        cout<<s[i].name<<":"<<s[i].num<<endl;
    }
    return 0;
}

10. Patient queuing

Please write a program in which patients line up to see a doctor.
The patient has three pieces of information: registration serial number, age and ID. The ID is a character string with a length less than 10. Each patient's ID is different and only contains numbers and letters.
The queuing rules are:
1. Elderly people (age ≥ 60 years old) have priority in seeing a doctor than non-elderly people.
2. The elderly see a doctor in descending order of age, and those of the same age are sorted in the order of registration.
3. Non-elderly people see a doctor in the order of registration.

enter description

In line 1, enter a positive integer less than 100, indicating the number of patients;
follow the order of patient registration, enter a patient ID and age in each line, separated by a single space.
The registration sequence number of the patient is 1~n, which is consistent with the input sequence of the patient.

output description

Patient IDs sorted by rule, one per line.

Use case input 1

5
021075 40
004003 15
010158 67
021033 75
102012 30

Use case output 1

021033
010158
021075
004003
102012
#include<iostream>
#include <bits/stdc++.h>
using namespace std;

struct s{
    
    
	char id[21];
	int age;
	int I;
};
s stu[100];
s old[100];
s young[100];
bool cmp_o(s x,s y){
    
    
    if(x.age==y.age){
    
    
        return x.I<y.I;
    }else{
    
    
        return x.age>y.age;
    }
}

bool cmp_y(s x,s y){
    
    
    return x.I<y.I;
}

int main()
{
    
    
	int n;
	cin>>n;
	for(int i=0;i<n;i++){
    
    
		cin>>stu[i].id>>stu[i].age;
		stu[i].I=i;
		cin.get();
	}
	
	int j=0,k=0;
	for(int i=0;i<n;i++){
    
    
		if(stu[i].age>=60){
    
    
			old[j++]=stu[i];
		}else{
    
    
			young[k++]=stu[i];
		}
	}
	//排序
	sort(old,old+j,cmp_o);
	sort(young,young+k,cmp_y);
	for(int i=0;i<j;i++){
    
    
		cout<<old[i].id<<endl;
	} 
	for(int i=0;i<=k;i++){
    
    
		cout<<young[i].id<<endl;
	} 
 } 

Guess you like

Origin blog.csdn.net/qq_43884946/article/details/130927741