注册 登录
编程论坛 C++教室

求平均值(无限for循环)

hmsabc 发布于 2010-08-21 12:56, 1767 次点击
程序代码:
//求平均值(无限for循环)

#include <iostream>
using namespace std;

int main( )
{
    double value = 0.0;
    double sum = 0.0;
    int i = 0;
    char indicator = 'n';

    for( ; ;)                                   //无任何表达式,只有两个分号
    {
        cout << endl
            << "Enter a value: ";
        cin >> value;
        ++i;
        sum += value;

        cout << endl
            << "Do you want to enter anolther value ( enter y or n) ? ";
        cin >> indicator;
        if ((indicator != 'y') && (indicator != 'n'))
            cout << endl <<"Your enter is worng !" << endl;
        if((indicator == 'y') || (indicator == 'Y'))
            cout << endl << "ok!";
        if((indicator == 'n')|| (indicator == 'N'))
            break;
    }
    cout << endl
        << "The average of the " << i
        << " Values you entered is " << sum / i << endl;
   
    system("pause");
    return 0;
}

值得注意的 for 循环。
5 回复
#2
yanzhuomin2010-08-21 22:08
怎么了 有问题?能结束呀 !
当你输入N是就结束了!
#3
书中叶2010-08-21 23:20
呵呵,楼主的代码很不错,又学到了知识~~
#4
书中叶2010-08-21 23:39
果然,我品味出for语句的实用了
#5
flyingcat2010-08-22 00:34
while(1)
{
   //add your code here
}

同样的效果……
#6
zgb5262010-09-01 17:41
里面能跳出,不是死循环。
1