繁体   English   中英

错误:“sumProduct”未在此范围内声明

[英]error: 'sumProduct' was not declared in this scope

所以问题是:编写一个程序来生成 [1, 10) 范围内的数字的乘积。

所以,我假设是 1*2、2*3、3*4 等的总值。n*n+1 直到 n = 9。

我的代码如下:

#include <iostream>
#include <string>

int main()
{
  int product = 1;

    for (product = 1; product< 10; ++product) {

        int sumProduct = product * (product + 1);

    }
  std::cout << sumProduct << std::endl;
}

我的错误:

In function 'int main()':
11:9: warning: unused variable 'sumProduct' [-Wunused-variable]
14:16: error: 'sumProduct' was not declared in this scope

阅读编译器给出的错误: 14:16: error: 'sumProduct' was not declared in this scope 每当您在语句块(即{ ... }声明变量时,这些变量只能在该块内访问。 更具体地说,变量一旦超出范围就会被销毁。 简单的解决方案是像这样在外面声明它们

int main()
{ // begin block 1
  int product = 1;
  int sumProduct = 0; // declare the variable here...
    for (product = 1; product< 10; ++product) { // begin block 2

        sumProduct = product * (product + 1);

    } // end block 2
  std::cout << sumProduct << std::endl;
} // end block 1 sumProduct will 'die' here

如果我认为您想要发生的事情是正确的,那么您的代码逻辑仍然存在问题。

您只是因为范围界定而面临这个问题。

sumProduct在这个循环中定义。

for (product = 1; product< 10; ++product) {
    int sumProduct = product * (product + 1);
} // sumProduct dies here.

因此,当您尝试在循环外访问它时,它将在该范围内不可见。

std::cout << sumProduct << std::endl; // not visible here.

我建议你在循环范围之外的块中定义sumProduct

像这样的东西:

#include <iostream>
#include <string>

int main()
{
    int product = 1;
    int sumProduct = 1;

    for (product = 1; product< 10; ++product) {
        sumProduct *= product;
    }

    std::cout << sumProduct << std::endl; // sumProduct is in the same scope. So, it is visible.
}

暂无
暂无

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

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