0

即使我设置了限制,我的 for 语句也会不断重复?(对不起,我对此完全陌生)我不知道如何防止它永远重复。即使不满足我设置的条件也会熄灭,这应该发生吗?

// Garbage Collection
#include <iostream>
#include <cmath>

using namespace std;

int main() {
  double reg, glass, met;
  double total;
  double reg_ratio, glass_ratio, met_ratio;

  cin >> reg;
  cin >> glass;
  cin >> met;

  total = met + glass + reg;

  cout << "The total number of bags is " << total << endl;

  met_ratio = met / total;
  reg_ratio = reg / total;
  glass_ratio = glass / total;

  cout << "The metal ratio is " << met_ratio << endl;
  cout << "The glass ratio is " << glass_ratio << endl;
  cout << "The regular ratio is " << reg_ratio << endl;

  if (met==reg==glass) {
    cout << "All garbage amounts are the same." << endl;
  }
  else if (reg > glass && met) {
    cout << "Regular is the largest." << endl;
  }
  else if (glass > met && reg) {
    cout << "Glass is the largest." << endl;
  }
  else if (met> glass && reg) {
    cout << "Metal is the largest." << endl;
  }

  for (reg >= 50; reg+reg;) {
    cout << "I can't take anymore." << endl;
  }

  return 0;
}  
4

3 回答 3

3

这不是 a 的for工作方式。它的:

for (initial statement; condition; iteration operation)

执行一次,在循环的initial statement第一次进入时,只要为condition真,循环就会执行,并且操作在每次迭代时执行。

在您的情况下,初始语句是reg >= 50,它什么都不做,条件是只有在以某种方式评估为reg+reg时才会为假,并且没有操作。reg+regfalse

reg+reg不会修改reg介意你。您正在寻找的操作可能是reg += reg.

于 2012-09-29T16:24:47.093 回答
3

for(initialization; condition; increment-code)是 for 循环的工作原理(注意:所有三个部分都是可选的)。如果conditiontrue,则继续循环。你把它混合起来写成for(condition; increment-code; *empty*). 请注意,您的情况似乎相反。此外,您的增量部分实际上并没有 update reg,您将其添加到自身并将结果丢弃。

正确的代码是

for(; reg <= 50; reg += reg)

另请注意,您的if陈述似乎非常虚假。

if (reg> glass && met)

首先,请在二元运算周围留一个空格。接下来,这将仅测试 iftreg是否大于glass并且是否met为非零值。要测试是否reg同时大于glass和大于met,您必须明确执行两次:

if(reg > glass && reg > met)

我可以推荐一本好书吗?

于 2012-09-29T16:24:54.473 回答
0

其他用户的报告是正确的:for你写的语句永远不会结束,也不会改变任何变量。Xeofor为您提供了编写语句的正确方法。

我要补充的是,for-loop 应该包含在条件为真时需要执行的指令。在您的情况下,您正在执行的指令似乎是在条件不再为真时执行的。如果你只是想在变量高于某个值时写一条消息,你应该使用if语句。

if (reg >= 50) {
  cout << "I can't take more." << endl;
}
于 2012-09-29T17:07:09.710 回答