首页 > 解决方案 > 仅当将(IF)循环合并到while循环中时才过早地强制结束while循环?

问题描述

该程序应该要求输入为向量输入一个变量,直到用户选择“-0”来停止while循环。在 While 循环中使用这个“IF”嵌套循环,它在停止程序之前允许 3 个条目!为什么?请找到“这就是这里;这是有问题的代码!” 请注意此代码块并尝试使用或不使用“if”语句的程序。

   int main(){
    std::vector<float> asdf;
    float g = 0; std::cout << "enter value g;" << endl;
    std::cin >> g; asdf.push_back(g);
    while (g != -0) {
        std::cout << "enter another g value" << endl;
        std::cin >> g;
        asdf.push_back(g);
    /* **THIS RIGHT HERE; THIS is the offending code!** */       if (g = -0) { asdf.pop_back(); }
    }   
    std::cout << "end of vector" << endl;
    for (int i = 0; i < asdf.size(); i++) { std::cout << asdf[i] << ", "; }
    std::cout << "end of while;" << endl;
    system("pause"); return 0;
    
}

谢谢

标签: c++if-statementwhile-loopc++14

解决方案


推荐阅读