即使设置了限制,我的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;
}

最佳答案

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

for (initial statement; condition; iteration operation)


initial statement执行一次,在循环的第一个条目上,只要condition为true,循环就执行一次,并且该操作在每次迭代时执行。

在您的情况下,初始语句为reg >= 50,不执行任何操作,条件为reg+reg,仅当reg+reg以某种方式计算为false且没有任何操作时,该条件才为false。

reg+reg不会修改reg提醒您。您要查找的操作可能是reg += reg

关于c++ - 即使设置了限制,我的for语句仍在重复?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12654332/

10-13 02:22