Cplus 实验一

习题2-28源码

if...else版本

#include<iostream>
using namespace std;
int main()
{
    cout<<"Menu:A(dd) D(elete) S(ort) Q(uit) Select one"<<endl;
    while(1){
    char selection;    
    int A,D,S,Q;
    cin>>selection;
    {
    if(selection=='A')
    cout<<"数据已经增加"<<endl;    
    else if(selection=='D')
    cout<<"数据已经删除"<<endl;
    else if(selection=='S')
    cout<<"数据已经排序"<<endl;
    else if(selection=='Q')
    break;}
}
    return 0; 
}

运行结果如图

 switch版本

#include<iostream>
using namespace std;
int main()
{
    cout<<"Menu:A(dd) D(elete) S(ort) Q(uit) Select one"<<endl;
    while(1){
    char(selection);
    int A,D,S,Q;
    cin>>selection;
    switch(selection){
    case'A':
        cout<<"数据已经增加"<<endl;
        break;
    case'D':
        cout<<"数据已经删除"<<endl;
        break;
    case'S':
        cout<<"数据已经排序"<<endl;
        break;
    }
    if(selection=='Q')
        break; 
    }
}

运行结果如图

习题2-29源码

while版本

#include <iostream>
#include <math.h>
using namespace std;
int main()
{
	int x,y,z,parameter;
	x=2;
	cout<<"1-100内质数有"<<" ";
	while(x<=100){
		y=1;
		parameter=sqrt(x);
		z=2;
		while(z<=parameter){
		if(x%z==0){
	    y=0;
	    break;}
	    z++;}
		if(y)
        cout<<x<<" ";
        x++;
	}
	}

 运行结果如图

do..while版本

#include <iostream>
#include <math.h>
using namespace std;
int main()
{
    int x,y,z,parameter;
    x=2;
    cout<<"1-100内质数有"<<" ";
    do{
        y=1;
        parameter=sqrt(x);
        z=2;
    do{
        if(x%z==0){
        y=0;
        break;}
        z++;}
        while(z<=parameter);
            if(y)
            cout<<x<<" ";
            x++;
            }
            while(x<=100);
}

运行结果如下

for版本

#include <iostream>
#include <math.h>
using namespace std;
int main()
{
    int x,y,z,parameter;
    cout<<"1-100内质数有"<<" ";
    for(x=2;x<=100;x++){
        y=1;
        parameter=sqrt(x);
    for(z=2;z<=parameter;z++){
        if(x%z==0){
        y=0;
        break;}}
        if(y)
        cout<<x<<" ";
    }
    }

运行结果如下

习题2-32源码

 while版本

#include<iostream>
using namespace std;
int main()
{
    int x,y;
    x=14;
    while(y!=x){
    cout<<"please input an number"<<endl;
    cin>>y;    
    if(y<x)
    cout<<"The number you guess is smaller than given"<<endl;
    else if(y>x)
    cout<<"The number you guess is bigger than given"<<endl;
    else
    cout<<"you are right"<<endl;}
}

(emmm懒得中英文切换了就打了蹩脚的英语)

运行结果如下

do...while版本

#include<iostream>
using namespace std;
int main()
{
    int x,y;
    x=14;
    do{
    cout<<"please input an number"<<endl;
    cin>>y;
    if(y<x)
    cout<<"The number you guess is smaller than given"<<endl;
    else if(y>x)
    cout<<"The number you guess is bigger than given"<<endl;
    else
    cout<<"you are right"<<endl;}
    while(y!=x);
}

运行结果如下

习题2-34源码

posted on 2019-03-18 11:49  宠溺  阅读(127)  评论(0编辑  收藏  举报

导航