【发布时间】:2016-01-21 04:09:26
【问题描述】:
我发现了一个帖子,其中使用了 FOR 循环而没有 CONDITION 值。这是一个循环:
for (INITIALIZATION; CONDITION; AFTERTHOUGHT)
{
// Code for the for-loop's body goes here.
}
跳过 CONDITION 值是不安全的,但如果你使用if/else 语句,它可以做到。请看一下我的 for 循环:for (int i = 1; ; i++) 和里面的实现。出于某种原因,if/else 语句我没有得到正确的逻辑。
#include <iostream>
using namespace std;
int main() {
int boxes;
int boxes_for_sale;
cout << "Enter quantity of the boxes in warehouse: > " << flush;
cin >> boxes;
cout << "Enter quantity of the boxes for sale: > " << flush;
cin >> boxes_for_sale;
for (int i = 1;; i++) {
if (boxes < boxes_for_sale) {
cout << "There are not enough boxes in warehouse!" << endl;
cout << "Enter quantity of the boxes for sale: > " << flush;
cin >> boxes_for_sale;
}
else
boxes -= boxes_for_sale;
cout << "Car N:" << i << " is full\n" << "You have " << boxes << "boxes for sale" << endl;
if (boxes == 0)
cout << "Sold out!" << endl;
break;
}
return 0;
}
【问题讨论】:
-
您在几个地方缺少一些大括号
{}。 -
正如@1201ProgramAlarm 所说,您需要在if 和else 语句之后将代码括起来。此外,“它不能正常工作”也不是一个好的问题描述。您应该添加有关如何它不起作用以及您预期会发生什么的信息。
标签: c++ if-statement for-loop