c++ ‘total’ 未在此范围内声明。主要的
c++ ‘total’ was not declared in this scope. MAIN
#include <iostream>
using namespace std;
int population(int current_pop)
{
int Time;
int birth;
int immigrant;
int death;
int total;
Time = 24*60*60*365; // convet day to second
birth = Time/8;
death = Time/12;
immigrant = Time/33; // calculate the rate of the death, birth,immigrant
total = birth+immigrant-death+current_pop; // make sum
return total;
}
int main() {
int current_pop = 1000000;
population(current_pop); //test
cout << total << endl;
}
它只是显示错误:“总计”未在此范围内声明
cout << 总计 << endl;
为什么?如果我已经声明了一个值,我应该在主函数中再次声明它吗?
不同函数中的同名变量存储不同的值。他们完全无关。开始编程时需要一些习惯。试试这个:
int total = population(current_pop); //test
如错误所述,您在 population()
中声明了 total
变量,这在 main()
函数中将不可用。 population()
函数将有自己的作用域,因此在其中声明的任何变量都只能在那里访问。
要使其可用,您需要在 main()
中声明它。
int main() {
...
int total = population(current_pop);
...
}
#include <iostream>
using namespace std;
int population(int current_pop)
{
int Time;
int birth;
int immigrant;
int death;
int total;
Time = 24*60*60*365; // convet day to second
birth = Time/8;
death = Time/12;
immigrant = Time/33; // calculate the rate of the death, birth,immigrant
total = birth+immigrant-death+current_pop; // make sum
return total;
}
int main() {
int current_pop = 1000000;
population(current_pop); //test
cout << total << endl;
}
它只是显示错误:“总计”未在此范围内声明 cout << 总计 << endl;
为什么?如果我已经声明了一个值,我应该在主函数中再次声明它吗?
不同函数中的同名变量存储不同的值。他们完全无关。开始编程时需要一些习惯。试试这个:
int total = population(current_pop); //test
如错误所述,您在 population()
中声明了 total
变量,这在 main()
函数中将不可用。 population()
函数将有自己的作用域,因此在其中声明的任何变量都只能在那里访问。
要使其可用,您需要在 main()
中声明它。
int main() {
...
int total = population(current_pop);
...
}