(1)输入一串字符串,字符串以“#”结尾,判断输入的字符串中0至9的个数。
#include<iostream>using namespace std;int main(){int sum = 0;string s;while(cin >> s){if(s == "#") break;int n = s.size();for(int i = 0; i < n; i ++){if(s[i] >= '0' && s[i] <= '9') sum ++;}}cout<<sum;return 0;
}
(2)输入学生的姓名和成绩,按照学生成绩进行排序后输出,要求用稳定的排序,flag表示正序、逆序输出。
#include<iostream>using namespace std;
const int N = 1e5+10;struct Stu{string name;string id;int grade;
}stu[N];int n,flag;
int main(){cin >> n >> flag;for(int i = 0; i < n; i ++){cin >> stu[i].name >> stu[i].id >> stu[i].grade;}for(int i = n - 1; i > 0; i --){for(int j = 0; j < i; j ++){if(flag == 1)if(stu[j].grade > stu[j+1].grade) swap(stu[j],stu[j+1]);elseif(stu[j].grade < stu[j+1].grade) swap(stu[j],stu[j+1]);}}cout<<stu[0].name<<" "<<stu[0].id<<"\n";cout<<stu[n-1].name<<" "<<stu[n-1].id<<"\n";return 0;
}
(3)输入年月日,求这是当年第几天。
#include<iostream>using namespace std;
const int N = 1e5+10;int date;
int month[] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
//1 3 5 7 8 10 12
//4 6 9 11
//2
bool isleap(int n){if(n % 400 == 0 ) return true;if(n % 4 == 0 && n % 100 != 0) return true;return false;
}
int main(){cin >> date;int year = date/10000;date%=10000;int mon = date/100;int day = date%100;int ans = 0;for(int i = 1; i < mon; i ++){if(mon == 2)if(isleap(year)) ans += 1;ans += month[i];}ans += day;cout<<ans;return 0;
}
(3)输入年月日,变形题:求当年第几天是几月几号。
#include<iostream>using namespace std;
const int N = 1e5+10;int year,date;
int month[] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
//1 3 5 7 8 10 12
//4 6 9 11
//2
bool isleap(int n){if(n % 400 == 0 ) return true;if(n % 4 == 0 && n % 100 != 0) return true;return false;
}
int main(){cin >> year >> date;int mon = 0,day = 0;int cnt = 0;if(isleap(year))month[2] ++;for(int i = 1; i <= 12; i ++){for(int j = 1; j <= month[i]; j ++){cnt ++;if(cnt == date){mon = i;day = j;}}} cout<<mon<<" "<<day;return 0;
}
(4)将m个相同的球全部放到n个相同的盒子里有多少种放法。(球本身视为相同)
待补