标题:请教一个使用++前缀作为控制条件的问题
取消只看楼主
jr9910
Rank: 1
等 级:新手上路
帖 子:14
专家分:0
注 册:2010-9-2
 问题点数:0 回复次数:2 
请教一个使用++前缀作为控制条件的问题
程序很简单,清单如下:
// cinfish.cpp -- non-numeric input terminates loop
#include <iostream>
const int Max = 5;

int main()
{
    using namespace std;

    //get  data
    double fish[Max];
    cout << "Please enter the weights of your fish.\n";
    cout << "You may enter up to " << Max
        << " fish <q to terminate>.\n";
    cout << "fish #1: ";
    int i = 0;
    while (i < Max && cin >> fish[i])
    {
        if (++i < Max)    // i为4时,条件已经为false,为什么还执行了cout的语句?
        {
            cout << "fish #" << i + 1 << ": ";
        }
    }

    // calculate average
    double total = 0.0;
    for (int j = 0; j < i; j++)
    {
        total += fish[j];
    }

    // report results
    if (i == 0)
    {
        cout << "No fish\n";
//        cin.clear();
    }
    else
    {
        cout << total / i << " = average weight of "
            << i << " fish\n";
    }
    cout << "Done.\n";

    cin.get();
    cin.get();
    return 0;
}
问题就出现在注释的位置:当i为4时,++操作符作为前缀使用,先加1,++i表达式的值为5,已经=Max了,条件不成立,为什么还输出了 fish #5:
搜索更多相关主题的帖子: 前缀 条件 
2010-09-07 22:44
jr9910
Rank: 1
等 级:新手上路
帖 子:14
专家分:0
注 册:2010-9-2
得分:0 
回复 2楼 最近不在
是,我确实正在看这本书,你也在看对吧,有时间可以交流!
2010-09-10 22:07
jr9910
Rank: 1
等 级:新手上路
帖 子:14
专家分:0
注 册:2010-9-2
得分:0 
回复 3楼 hdshdzh
这个位置处理的真微妙!
2010-09-10 22:32



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-319529-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.244099 second(s), 8 queries.
Copyright©2004-2025, BCCN.NET, All Rights Reserved