【问题标题】:Runtime error in nested for loop C++嵌套 for 循环 C++ 中的运行时错误
【发布时间】:2016-02-07 22:12:59
【问题描述】:
 for(i=0;i<np;i++){
    cin >> temp_str;
    pos = find(names.begin(), names.end(), temp_str) - names.begin();
    cin >> total >> ppl;
    giving.push_back(make_pair(pos, total));
    amt_getting = total / ppl;
    bal[pos] += total - (amt_getting * ppl);

    for(j = 0; j < np - 1; j++){   /**** Error due to this loop's condition******/
       cin >> temp_str;
       pos = find(names.begin(), names.end(), temp_str) - names.begin();
       bal[pos] += amt_getting;
    }

我的程序出现运行时错误。这是 RTE 发生的代码片段。每当我将条件 j &lt; np-1 更改为 j &lt; np 时,错误就会得到修复。怎么了?我什至没有在第二个for 循环中使用任何数组来处理段错误。

【问题讨论】:

  • 什么是np?它的价值是什么?
  • ijintunsigned int 还是 ...?
  • 请附上相关且有效的代码以及错误声明。
  • 请记录 i 和 j 的值;并在出现段错误时告诉我们他们的 val。另外,如果它认为你“甚至没有在第二个 for 循环中使用任何数组”,bal是一个关联容器?
  • @Raul 这是一个糟糕的建议。他们应该使用重现问题的相关代码将问题减少到最小但完整的示例。

标签: c++ for-loop error-handling runtime-error


【解决方案1】:

你没有提到什么样的运行时错误,所以这是猜想......

使用np - 1,您的代码与输入不匹配;流中还剩下一个非整数。

这意味着cin &gt;&gt; total &gt;&gt; ppl 失败,ppl 变为零,total / ppl 被零除。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-12
    • 2012-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-14
    • 2019-03-17
    相关资源
    最近更新 更多