#include<bits/stdc++.h> using namespace std; bool rn(int c) { bool a=0; if((c%4==0 and c%100!=0) or c%400==0) a=1; return a; } int main() { int a,b,ans=0,d[3000-1582]; scanf("%d%d",&a,&b); for(int i=a;i<=b;i++) { if(rn(i)) ans++; d[ans]=i; } printf("%d\n",ans); for(int i=0;i<ans;i++) { printf("%d ",d[i]); } return 0; }代码有什么问题
时间: 2023-12-01 09:02:57 浏览: 94
你的代码似乎存在以下几个问题:
1. 函数 `rn` 的返回值类型为 bool,但是在函数内部使用了整型变量 a 进行赋值。虽然 C++ 中可以将整型变量隐式转换为布尔类型,但是最好还是将返回值类型改为 int 类型。
2. 在循环中,当判断当前年份是闰年时,你只是将 a 设为 1,但并没有使用这个值。因此,即使当前年份是闰年,ans 的值也不会增加。你需要将 ans++ 的操作放在 if 语句的外面。
3. 在存储闰年的数组 d 中,你将 ans 的值作为数组下标,但是 ans 是表示当前已经找到的闰年数量,因此数组的最大下标应该是 ans-1,而不是 ans。
下面是修改后的代码:
```cpp
#include <bits/stdc++.h>
using namespace std;
int rn(int c) {
if ((c % 4 == 0 && c % 100 != 0) || c % 400 == 0)
return 1;
return 0;
}
int main() {
int a, b, ans = 0, d[3000 - 1582];
scanf("%d%d", &a, &b);
for (int i = a; i <= b; i++) {
if (rn(i)) {
d[ans] = i;
ans++;
}
}
printf("%d\n", ans);
for (int i = 0; i < ans; i++) {
printf("%d ", d[i]);
}
return 0;
}
```
阅读全文
相关推荐










