各位帮我看看,这两个有什么区别,为什么造成结果不一样


```c
 #include  
int check(int n);
void check_year(int year);
long long count = 0;
int months[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
int main()
{
     
    int year, month, day;

    for (year = 1900; year <= 9999; year++)
    {
     
        if (check(year))
            count++;
        for (month = 1; month <= 12; month++)
        {
            if (check(month))
                count++;
        }
        for (day = 1; day <= months[month]; day++)
        {
            if (check(day))
                count++;
        }
    }
    printf("总共有%llu个2", count);
    return 0;
}
void check_year(int year)
{
        if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
            months[2] = 29;
        else
            months[2] = 28;
}
int check(int n)
{
    while (n)
    {
        if (n % 10 == 2)
        {
            return 1;
            break;
        }
        n /= 10;
    }
    return 0;
}



//上下两程序明明都是求数字2有多少为什么第一个程序不行,明明逻辑都一样。






#include 
using namespace std;

int days[] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

bool is_leap(int year)
{
    return year % 400 == 0 || year % 4 == 0 && year % 100 != 0;
}

bool check1(int x)
{
    int year = x / 10000;
    int month = x / 100 % 100;
    int day = x % 100;

    if (month < 1 || month > 12) return false;
    if (month != 2)
    {
        if (day < 1 || day > days[month]) return false;
    }
    else
    {
        if (day < 1 || day > days[month] + is_leap(year)) return false;
    }
    return true;
}

bool check2(int x)
{
    while (x)
    {
        if (x % 10 == 2) return true;
        x /= 10;
    }
    return false;
}

int main()
{
    int ans = 0;
    for (int i = 19000101; i <= 99991231; i++)
        if (check1(i) && check2(i))
            ans++;

    cout << ans << endl;
    return 0;
}

这两个程序的确都是求数字2有多少个,但是两个程序的实现方式有很大的区别,因此得出的结果不同。

首先,第一个程序中在遍历每个月份和日期的时候,month 和 day 都是从1开始遍历的,而不是根据实际的年份和月份确定的。因此,这个程序的实现方式是有问题的。
望采纳🥰🥰🥰
其次,第一个程序在计算闰年的时候,只修改了全局变量 months 数组中的2月份的天数,但没有在每一年开始时重新计算该年是否为闰年,也没有更新其他月份的天数。因此,在计算日期时会出现错误。

第二个程序中,check1函数是用来检查日期是否合法的,而check2函数是用来检查数字2是否在日期中出现。它们的实现方式是比较简单直接的,没有明显的问题。

因此,第二个程序的结果更可靠。如果你想要实现一个类似的程序,可以参考第二个程序的实现方式。

第一段23行有问题,这时候month等于13。应该把23行这个for循环放到前面一个循环体内


 #include <stdio.h> 
int check(int n);
void check_year(int year);
long long count = 0;
int months[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
int main()
{
     
    int year, month, day;
 
    for (year = 1900; year <= 9999; year++)
    {
     
        if (check(year))
            count++;
        for (month = 1; month <= 12; month++)
        {
            if (check(month))
                count++;
            for (day = 1; day <= months[month]; day++)
            {
                if (check(day))
                    count++;
            }
        }
       
    }
    printf("总共有%llu个2", count);
    return 0;