简体   繁体   English

未在此范围内声明的变量错误的问题

[英]problem with error in variable not declared in this scope

Hello guys this is my first time using stackoverflow and hope that you would oblige me.大家好,这是我第一次使用 stackoverflow,希望你们能帮到我。

so I was learning coding from codecademy and I was stuck in this project所以我从codecademy学习编码,我被困在这个项目中

Question- Write a program to find the sum of even numbers and the product of odd numbers in a vector.问题 -编写一个程序来计算向量中偶数之和和奇数之积。

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

error being shown-显示错误-

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

You cannot access variables outside of their scope.您不能访问其范围之外的变量。 Thats what the error says.这就是错误所说的。 Your code reduced to the bare minimum is:您的代码减少到最低限度是:

 int main() {
     bool condition = true;
     if (condition) {
          int x = 0;
     }
     x = 42;                  // error not declared in this scope
 }

And the same without the error:同样没有错误:

 int main() {
     bool condition = true;
     int x = 0;
     if (condition) {
          x = 0;
     }
     x = 42;                 
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM