1定义一个结构类型数组(包括年、月、日),实现输入十个日期,按日期从大到小排序输出。
#include <stdio.h>
struct Date {
int year;
int month;
int day;
};
int compare(struct Date d1, struct Date d2) {
if (d1.year != d2.year) {
return d2.year - d1.year;
} else if (d1.month != d2.month) {
return d2.month - d1.month;
} else {
return d2.day - d1.day;
}
}
int main() {
struct Date dates[10];
int i;
// 输入10个日期
for (i = 0; i < 10; i++) {
printf("请输入第%d个日期(年 月 日):", i + 1);
scanf("%d%d%d", &dates[i].year, &dates[i].month, &dates[i].day);
}
// 按日期从大到小排序
for (i = 0; i < 9; i++) {
int max = i;
int j;
for (j = i + 1; j < 10; j++) {
if (compare(dates[max], dates[j]) < 0) {
max = j;
}
}
struct Date tmp = dates[i];
dates[i] = dates[max];
dates[max] = tmp;
}
// 输出排序后的日期
for (i = 0; i < 10; i++) {
printf("%d-%02d-%02d\n", dates[i].year, dates[i].month, dates[i].day);
}
}
#include <iostream>
using namespace std;
int main()
{
const int i=1;
while(i==1)
{
int Y,M,D,y,m,H,min; float J,sec;
cin>>Y>>M>>D>>H>>min>>sec;
if(M>=3)
{
y=Y;
m=M-3;
}
else
{
y=Y-1;
m=M+9;
};
J=1721103.5+int(365.25*y)+int(30.6*m+0.5)+D;
cout.setf(ios::fixed,ios::floatfield);//使结果不使用科学记数法
cout.precision(4);//保留n位小数
cout<<"JD"<<J+(double)H/24+(double)min/1440+(double)sec/86400<<endl;
cout<<"MJD"<<J+(double)H/24+(double)min/1440+(double)sec/86400-2400000.5<<endl<<endl;
}
return 0;
}
输入示例:
输出示例:
还可以继续处理多个:
根据参考资料中的第一个代码段和第二个代码段,结合问题内容,我可以给出以下解决方案:
struct Date{
int year;
int month;
int day;
};
struct Date dates[10];
printf("请输入十个日期(年 月 日):\n");
for(int i=0; i<10; i++){
scanf("%d %d %d", &dates[i].year, &dates[i].month, &dates[i].day);
}
for(int i=0; i<10-1; i++){
for(int j=0; j<10-1-i; j++){
if(compareDates(dates[j], dates[j+1]) < 0){
swapDates(&dates[j], &dates[j+1]);
}
}
}
compareDates()
和交换日期的函数 swapDates()
。int compareDates(struct Date date1, struct Date date2){
if(date1.year < date2.year)
return -1;
else if(date1.year > date2.year)
return 1;
else{
if(date1.month < date2.month)
return -1;
else if(date1.month > date2.month)
return 1;
else{
if(date1.day < date2.day)
return -1;
else if(date1.day > date2.day)
return 1;
else
return 0; // 日期相等
}
}
}
void swapDates(struct Date *date1, struct Date *date2){
struct Date temp = *date1;
*date1 = *date2;
*date2 = temp;
}
printf("按日期从大到小排序的结果:\n");
for(int i=0; i<10; i++){
printf("%d年%d月%d日\n", dates[i].year, dates[i].month, dates[i].day);
}
通过以上步骤,我们可以实现按日期从大到小排序的功能。如果你还有其他问题或需要进一步的解释,请随时提问。