【问题标题】:Variable doesn't change its value during a for-loop statement [closed]变量在 for 循环语句期间不会更改其值 [关闭]
【发布时间】:2021-09-25 16:27:27
【问题描述】:

正在尝试实施埃拉托色尼筛法以查找最大为 100 的所有素数。产品似乎没有改变。是什么原因?

#include <iostream>
#include <vector>

int main()
{   
    int counter = 0;
    int multicand = 2;
    std::vector<int> non_prime;
    
    for (int product = multicand * 2; product < 100; multicand++){
        std::cout << product << '\n' << multicand << '\n';
        
        counter++;
        if (counter == 50) return 0;
    }
}

【问题讨论】:

  • 你在哪里改?
  • 可能在std::cout 中说product++;你的意思是增加multicand?
  • 我在for-statement初始化中指定了产品
  • 因为没有声明要更新product。您可能需要将multicand++ 更改为product = ++multicand * 2
  • 谢谢大家,我现在明白了

标签: c++ infinite-loop


【解决方案1】:

在你的 for 循环中,你只是增加变量 multicand。

当你这样做时:for (int product = multicand * 2; product &lt; 100; multicand++){}

您是在对编译器说:声明一个名为 product 的变量并将其设置为 multicand * 2,然后在 product 小于 100 时进行循环,并在循环的每个循环中将变量 multicand 加一。

【讨论】:

    猜你喜欢
    • 2022-01-14
    • 2017-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多