1

好的,所以我正在学习 C++,其中一个挑战是制作一个从 10 倒数到 -5 的程序。它总是从 9 到 1,它说完成了!

请以任何方式帮助我,这是代码:

/*
*
*   Negative Example
*
*/
#include <iostream>
#include <string>
int main()
{
signed int i = 10;
    for(i <= 10 && i != (0 - 5); --i;) {
        using std::cout;
        cout << i << std::endl;
    }
    std::cout << "Done!" << std::endl;
}

输出: 9 8 7 6 5 4 3 2 1 完成!

4

4 回答 4

2

As @jogojapan suggests, you want to rewrite

 for(i <= 10 && i != (0 - 5); --i;) {

as

for(i = 10 ; i != (0 - 5); --i) {

preferably as (although no difference functionally)

for(i = 10 ; i > - 5; --i) {

You can also define i within the loop body itself, if it is not needed before or after it, like so

for(int i = 10 ; i > - 5; --i) {

Edit: Change i>-5 to i>=-5 if you want the loop to run with i=-5 as well.

于 2012-12-18T02:29:08.937 回答
1
for(i <= 10 && i != (0 - 5); --i;) {

您将这些语句放在错误的位置,应该是:

for(;i <= 10 && i != (0 - 5); --i) { // or (0 - 5 - 1) if you want -5 as well

它从 9 开始并在 0 终止的原因是因为您使用--i的是持续条件。

该条件有一个副作用,即在循环体运行i 之前它会递减(即从 9 开始),并且在它达到 0 的那一刻它将是错误的。

为了更好地理解,请考虑for (x;y;z)

  • x在第一次迭代之前执行一次。
  • yis 在每次循环迭代之前评估,如果为 true,则循环继续(false 表示循环退出)。
  • z在循环的每次迭代之后执行。

当然,如果你想要一个从 10 到 -5(含)的循环,只需使用:

for (int i = 10; i >= -5; i--)

并停止使用狡猾的代码:-)

于 2012-12-18T02:28:56.663 回答
1

The issue with your code is that you have misplaced the parts of the for loop. As it is, the loop begins by evaluating the condition, and then proceeds to decrement i each time through, and check that this i is not equal to zero. The fact that your code completes is a consequence of the fact that --i will evaluate to 0 (false) if i == 1.

Your code should look like this:

#include <iostream>
#include <string>
int main()
{
    // Move the variable initialization to the first part of the loop
    signed int i;

    // Note the difference in where the expressions are placed
    // relative to the semicolons.
    for(i = 10; i <= 10 && i != (0 - 5); --i) {
        using std::cout;
        cout << i << std::endl;
    }
    std::cout << "Done!" << std::endl;
}
于 2012-12-18T02:30:43.533 回答
0

我认为你与中期不匹配。foreach 循环作为括号内的 3 个术语,即使您不使用它们,您仍然需要 2 个分号。您的中间期限目前是 --i ,只有当 i 为 0 时才会返回 false。

此外,与 C 不同的是,C++ 中的 for 循环与 for 循环具有不同的初始化部分,而在 C 中,您可以声明如下。. .

int i;
for (i=0; i < 10; ++i)

在 C++ 中,您可以这样声明循环内的变量。. .

for (int i=0; i < 10; ++i)
于 2012-12-18T02:34:22.863 回答