“未在此范围内声明”错误 [英] 'was not declared in this scope' error

查看:824
本文介绍了“未在此范围内声明”错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在编写此简单程序,以使用发现的高斯算法计算任何日期的日期。在这里

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

#include <iostream>
using namespace std;

//Using the Gaussian algorithm
int dayofweek(int date, int month, int year ){
    int d=date;
    if (month==1||month==2)
        {int y=((year-1)%100);int c=(year-1)/100;}
    else
        {int y=year%100;int 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;
}

int main(){
    cout<<dayofweek(19,1,2054);
    return 0;
}

这是一个非常简单的程序,更令人困惑的是输出。

It's a very simple program and what's even more puzzling is the output.

:In function  dayofweek(int, int, int)’:
:19: warning:  unused variable ‘y’
:19: warning: unused variable ‘c’
:21: warning: unused variable ‘y’
:21: warning: unused variable ‘c’
:23: error: ‘y’ was not declared in this scope
:25: error: ‘c’ was not declared in this scope

它说我的变量未使用,但随后又说它没有声明?任何人都可以告诉我怎么了。

It says that my variable is unused but then says that it isn't declared? Could anyone please tell me whats wrong.

推荐答案

变量的范围始终是其内部的块。例如,如果您执行类似的操作

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.

解决方案是在if块之外定义y

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

在程序中,必须将y和c的定义移出if块进入更高的范围。然后,您的函数将如下所示:

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;
}

这篇关于“未在此范围内声明”错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆