gpt4 book ai didi

c++ - “未在此范围内声明”错误

转载 作者:IT老高 更新时间:2023-10-28 21:57:38 26 4
gpt4 key购买 nike

所以我正在编写这个简单的程序来使用找到的高斯算法计算任何日期的天数 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;
}

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

: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

它说我的变量未使用但又说它没有声明?谁能告诉我怎么了。

最佳答案

变量的范围总是它所在的 block 。例如,如果您执行类似的操作

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 block 之外定义 y

int y; //y is created

if(...)
{
y = 5;
}
else
{
y = 8;
}

cout << y << endl; //Ok

在您的程序中,您必须将 y 和 c 的定义从 if block 移到更高的范围。您的函数将如下所示:

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

关于c++ - “未在此范围内声明”错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10056093/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com