《N诺机试指南》(八)日期、字符串、排序问题
2024-10-08 19:16:49
1.日期问题:
输入:
例题:
代码:
#include <stdio.h>
#include <bits/stdc++.h>
struct node{
int year, mouth, day;
}p;
int f[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int main(){
while( scanf("%d%d%d", &p.year, &p.mouth, &p.day)!=EOF ){
//1.首先判断是不是闰年
if( (p.year%400==0)||(p.year%4==0 && p.year%100!=0) ){
f[2] = 29;//是闰年,二月为29天
}else{
f[2] = 28;//不是闰年
}
//2.判断输入的年月日是否合法
int flag = 0;
//2.1.判断月份
if( p.mouth<1 || p.mouth>12 ){
flag = 1;
}
//2.2.判断日
for( int i=1; i<=12; i++ ){
if( p.day<1 || p.day>f[i] ){
flag = 1;
}
}
if( flag ){
printf("Input Error\n");
}
//3.计算当前日子是第多少天
int sum = 0;
int nowDay = p.day;
for( int i=1; i<p.mouth; i++ ){
sum += f[i];
}
sum += nowDay;
printf("%d\n", sum);
}
return 0;
}
注意点:
怎么判断闰年:
(p.year%400==0)或者(p.year%4==0 && p.year%100!=0)
2.字符串问题:
例题:
代码:
#include <stdio.h>
#include <string.h>
#include <bits/stdc++.h> int main(){
char s[105];
gets(s);//输入一行文本
int len = strlen(s);
for(int i=0; i<len; i++){
//大写字母or小写字母
if(s[i]>='A' && s[i]<='Z'){
s[i] += 3;
}else if(s[i]>='a' && s[i]<='z'){
s[i] += 3;
}else{
//其他的不处理
continue;
}
}
puts(s);//输出一行文本
return 0;
}
3.排序问题:
sort函数:
例题:
解析:
代码:
#include <bits/stdc++.h>
using namespace std; /*
//问题一:稳定排序
struct Student{
string name;
int score, id;
}stu[1005]; //自定义:从小到大函数
bool FromShortToBig(Student a, Student b){
if( a.score==b.score ){
return a.id < b.id;//一样大,根据id判断
}
return a.score < b.score;//哪个小哪个在前面
}
//自定义:从大到小函数
bool FromBigToShort(Student a, Student b){
if( a.score==b.score ){
return a.id < b.id;//一样大,根据id判断
}
return a.score > b.score;//哪个大哪个在前面
} int main(){
int n, model;
cin >> n;
cin >> model;
//输入数据
for(int i=0; i<n; i++){
cin >> stu[i].name >> stu[i].score;
stu[i].id = i;//给id赋值
}
//判断哪种模式
if( model==0 ){
sort(stu, stu+n, FromBigToShort);
}else{
sort(stu, stu+n, FromShortToBig);
}
//打印
for(int i=0; i<n; i++){
cout << stu[i].name << " " << stu[i].score << endl;
}
return 0;
}
*/ //问题二:先奇后偶、再按从小到大顺序排序
bool cmp(int a, int b){
if( a%2==b%2 ){//同为奇数or偶数:按从小到大顺序排序
return a < b;
}else{
return a%2 > b%2;//不同:按先奇后偶顺序排序
}
} int main(){
int n;
cin >> n;
int a[n];
for(int i=0; i<n; i++){
cin >> a[i];
}
sort(a, a+n, cmp);
for(int i=0; i<n; i++){
cout << a[i] << " ";
}
cout << endl;
return 0;
}
最新文章
- 【原】Bootstrap+Knockout.JS+ASP.Net MVC3+PetaPOCO实现CRUD操作
- 重温Servlet学习笔记--request对象
- JDK源码分析:hashCode()方法
- Matlab绘图详解
- 数据绑定表达式(上):.NET发现之旅(一)
- C# sogou地图API应用总结
- OC语言中类目,延展,协议
- 獲取 Textarea 的光標位置(摘自網絡)
- Python 多线程 队列 示例
- jquery插件datepicker
- 第三章 视图和URL配置
- Vue(小案例_vue+axios仿手机app)_购物车(二模拟淘宝购物车页面,点击加减做出相应变化)
- POJ 1064 Cable master (二分法+精度控制)
- AndroidStudio制作个人资料界面模块以及SQLite数据库的使用
- PL/SQL Developer从11.0.6版本开始32/64为之区分
- php实现一个单链表
- linux下安装mysql等信息
- Spring(十五):通过注解配置 Bean
- spring整合ehcache注解实现查询缓存,并实现实时缓存更新或删除
- setTimeout() 实现程序每隔一段时间自己主动运行