'was not declared in this scope' error

前端 未结 5 742
难免孤独
难免孤独 2020-12-01 15:55

So I was writing this simple program to calculate the day of any date using the Gaussian algorithm found here.

#include 
using namespace std;         


        
5条回答
  •  一个人的身影
    2020-12-01 16:33

    The scope of a variable is always the block it is inside. For example if you do something like

    if(...)
    {
         int y = 5; //y is created
    } //y leaves scope, since the block ends.
    else
    {
         int y = 8; //y is created
    } //y leaves scope, since the block ends.
    
    cout << y << endl; //Gives error since y is not defined.
    

    The solution is to define y outside of the if blocks

    int y; //y is created
    
    if(...)
    {
         y = 5;
    } 
    else
    {
         y = 8;
    } 
    
    cout << y << endl; //Ok
    

    In your program you have to move the definition of y and c out of the if blocks into the higher scope. Your Function then would look like this:

    //Using the Gaussian algorithm
    int dayofweek(int date, int month, int year )
    {
        int y, c;
        int d=date;
    
        if (month==1||month==2)
        {
             y=((year-1)%100);
             c=(year-1)/100;
        }
        else
        {
             y=year%100;
             c=year/100;
        }
    int m=(month+9)%12+1;
    int product=(d+(2.6*m-0.2)+y+y/4+c/4-2*c);
    return product%7;
    }
    

提交回复
热议问题