C++编程实例-while循环结构

来源:互联网 发布:素书 知乎 编辑:程序博客网 时间:2024/05/29 19:37

实验2 while循环结构

【实验目的】

通过本实验,掌握循环结构程序设计的编程方法,掌握循环方面的编程技巧。

【实验要求】

⑴学会使用while语句;

⑵掌握循环结构程序设计方法;

【实验内容】

以下程序任选两个

从键盘上输入一组数(以输入0为结束),求累加和,并找出最大/小值。

#include<iostream>

using namespace std;

int main(){

    int i=1,sum=0,x,max,min;

    float r;

    cout<<"Input No."<<i<<" number: ";

    cin>>x;

    max=x; min=x;

    while(x!=0){

        sum+=x;

        i++;

        if(max<x) max=x;

        if(min>x) min=x;

        cout<<"Input No."<<i<<" number: ";

        cin>>x;

    }

    i--; r=(float)sum/i;

    cout<<"Average="<<r<<endl<<"Max="<<max<<"/nMin="<<min<<endl;

    return 0;

}

判断素数

#include<iostream>

using namespace std;

int main(){

    int x;

    cout<<"Please Input a number: "; cin>>x;

    int f=2;

    while(x%f!=0)

        f++;

    if(x==f)

        cout<<x<<" is prime number./n"<<endl;

    else

        cout<<x<<" is not prime number./n"<<endl;

    return 0;

}

判断从键盘上输入的一串字符中小写字母、数字字符及其它字符的数量。

#include<iostream>

using namespace std;

int main(){

    char ch;

    int n1=0,n2=0,n3=0;

    cout<<"Input some characters: ";  cin>>ch;

    while(ch != '?'){

        if((ch>='a')&&(ch<='z')) n1++;

        else if ((ch>='0')&&(ch<='9')) n2++;

             else n3++;

        cin>>ch;

    }

    cout<<"/nn1="<<n1<<"/nn2="<<n2<<"/nn3="<<n3;

    return 0;

}