|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本题要求编写程序计算某年某月某日是该年中的第几天。
输入格式:
输入在一行中按照格式“yyyy/mm/dd”(即“年/月/日”)给出日期。注意:闰年的判别条件是该年年份能被4整除但不能被100整除、或者能被400整除。闰年的2月有29天。
输出格式:
在一行输出日期是该年中的第几天。
输入样例1:
2009/03/02
输出样例1:
61
输入样例2:
2000/03/02
输出样例2:
62
我这样写代码哪里错了
#include<iostream>
using namespace std;
int main()
{
int year,month,day;int arr[12];
char ch,ch1;
cin>>year>>ch>>month>>ch1>>day;
if((year%4==0&&year%100!=0)||year%400==0)
{
arr[12]={31,29,31,30,31,30,31,31,30,31,30,31};
}
else
{arr[12]={31,28,31,30,31,30,31,31,30,31,30,31};
}
int sum=0;int i;
for(i=0;i<=month-2;i++)
{
sum+=arr[i];
}
sum+=day;
cout<<sum<<endl;
}
你的代码有几个问题。首先,你没有正确读取输入的年份、月份和日期,应该使用字符串来读取整个日期,然后再将其拆分为年、月和日。其次,你在声明数组 arr 的时候有语法错误,应该先声明再赋值。最后,你在计算总天数时,应该是从 1 月开始累加到给定月份的前一个月,而不是从 0 月开始累加。
以下是修改后的代码:
#include<iostream>
using namespace std;
int main()
{
int year, month, day;
int arr[12];
char ch, ch1;
string date;
cin >> date;
year = stoi(date.substr(0, 4));
month = stoi(date.substr(5, 2));
day = stoi(date.substr(8, 2));
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
{
int arr[] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
}
else
{
int arr[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
}
int sum = 0;
for (int i = 0; i < month - 1; i++)
{
sum += arr[ i];
}
sum += day;
cout << sum << endl;
return 0;
}
希望对你有帮助!如果你还有其他问题,请随时提问。
|
|