c++ - 未在此范围内声明的变量中的错误问题
问题描述
大家好,这是我第一次使用stackoverflow,希望你能答应我。
所以我正在从codecademy学习编码,我被困在这个项目中
问题 -编写一个程序来计算向量中偶数的和与奇数的乘积。
//my code
#include <iostream>
#include <vector>
int main()
{
std::cout << " This program is written to calculate the sum of even numbers and product of odd numbers\n";
std::cout << "When you are done then plz press f";
std::string ans;
int k;
std::cin >> ans;
while (ans != "f") {
std::cout << "Plz enter your number:";
std::cin >> k;
std::vector<int> num;
num.push_back(k);
}
if (ans == "f") {
std::cout << "Thanks for trying this program\n"
<< "your Answers are\n";
for (int i = 0; i <= num.size(); i++)
if (num[i] % 2 == 0) {
int even = even + num[i];
}
else {
int odd = odd + num[i];
}
}
std::cout << "Sum of even numbers is " << even << "\n";
std::cout << "Sum of odd numbrs is " << odd << "\n";
}
显示错误-
review.cpp: In function ‘int main()’:
review.cpp:18:26: error: ‘num’ was not declared in this scope
for (int i = 0; i <= num.size() ;i++)
^~~
review.cpp:18:26: note: suggested alternative: ‘enum’
for (int i = 0; i <= num.size() ;i++)
^~~
enum
review.cpp:26:47: error: ‘even’ was not declared in this scope
std::cout << "Sum of even numbers is " << even << "\n";
^~~~
review.cpp:27:45: error: ‘odd’ was not declared in this scope
std::cout << "Sum of odd numbrs is " << odd << "\n";
^~~
review.cpp:27:45: note: suggested alternative: ‘void’
std::cout << "Sum of odd numbrs is " << odd << "\n";
^~~
void
解决方案
您不能访问其范围之外的变量。这就是错误所说的。您的代码减少到最低限度是:
int main() {
bool condition = true;
if (condition) {
int x = 0;
}
x = 42; // error not declared in this scope
}
同样没有错误:
int main() {
bool condition = true;
int x = 0;
if (condition) {
x = 0;
}
x = 42;
}
推荐阅读
- python - Unabe 在 Beautifulsoup 中解析大表
- android - 检索 JSON 中的特定字段
- javascript - 在我的 Web 应用程序中为不同的打印对象设置本地打印机
- reactjs - Redux Form FieldArray 传递状态问题
- r - 如何存储 Highcharter 地图以便在没有 Internet 连接的情况下使用它们?
- php - 如何在 AJAX 调用后 JSON 值后更新同一页面上的 SESSION 值而不刷新页面
- spring-boot - 我们如何将默认的 Swagger URL 更改为任何其他 URL
- tensorflow - 尝试使用 EarlyStopping 和 f1-metric 作为停止标准时出现 TypeError
- sql - 只打印列中的最大值
- javascript - 使用 Javascript 和 Flask 进行视频流时的 URL 重定向