实验二

一、分别用switch和if···else语句

#include<iostream>
using namespace std;

int main()
{
char i;
cout << "Menu:" << endl << "A(dd)" << endl << "D(elete)" << endl << "S(ort)" << endl << "Q(uit)" << endl << "select one:" << endl;
while (1)
{
cin >> i;
if (i == 'A')
{
cout << "数据已经增加" << endl;
continue;
}
if (i == 'D')
{
cout << "数据已经删除" << endl;
continue;
}
if (i == 'S')
{
cout << "数据已经排序" << endl;
continue;
}
if (i == 'Q')
break;
}
return 0;
}

 

 

#include<iostream>
using namespace std;

int main()
{
char i;
cout << "Menu:"<<endl<<"A(dd)"<<endl<<"D(elete)"<<endl<<"S(ort)"<<endl<<"Q(uit)"<<endl<<"select one:" << endl;
while (1)
{
cin >> i;
switch (i)
{
case 'A':
cout << "数据已经增加" << endl;
break;
case 'D':
cout << "数据已经删除" << endl;
break;
case 'S':
cout << "数据已经排序" << endl;
break;
case 'Q':
exit(0);
default:
cout << "输入错误" << endl;
break;
}
}
return 0;
}

二、分别用for、while、do···while循环语句

#include<iostream>
#include<math.h>
using namespace std;

int main()
{
int i,j,k,a;
cout << "1~100内的质数有" << endl;
for (i = 2; i <= 100; i++)
{
k = 0;
a = sqrt(i);
for (j = 2; j <= a; j++)
{
if (i % j == 0)
{
k = 1;
break;
}
}
if (k == 0)
cout << i << endl;
}
return 0;
}

 

#include<iostream>
#include<cmath>
using namespace std;

int main()
{
int i = 2, j , k, m;
cout << "1~100内的质数为" << endl;
while (i <= 100)
{
m = 1;
k = sqrt(i);
j = 2;
while (j <= k)
{
if (i%j == 0)
{
m = 0;
break;
}
j++;
}
if (m)
cout << i << endl;
i++;
}
return 0;
}

 

#include<iostream>
#include<cmath>
using namespace std;

int main()
{
cout << "1~100的质数有" << endl;
int i, j, k, m;
i = 2;
do
{
m = 1;
k = sqrt(i);
j = 2;
do
{
if (i == j)
{
break;
}
if (i%j == 0)
{
m = 0;
break;
}
j++;
} while (j <= k);
if (m)
cout << i << endl;
i++;
} while (i <= 100);
return 0;
}

 

三、分别用while、do···while循环语句

#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;

int random(int fanwei)
{
srand((unsigned)time(NULL));
return rand() % fanwei;
}

int main()
{
int x, a;
x = random(100);
cout << "请猜数字" << endl;
cin >> a;
if (a == x)
cout << "猜对了!" << endl;
while (a != x)
{
if (a > x)
cout << "太大了" << endl;
else cout << "太小了" << endl;
cin >> a;
}
return 0;
}

 

#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;

int random(int fanwei)
{
srand((unsigned)time(NULL));
return rand() % fanwei;
}

int main()
{
int x, a;
x = random(100);
cout << "请猜数" << endl;
do
{
cin >> a;
if (a > x)
cout << "猜大了" << endl;
else if (a < x)
cout << "猜小了" << endl;
else cout << "猜对了!" << endl;
} while (a != x);

return 0;
}

 

#include<iostream>
using namespace std;

int jiecheng(int a)
{
int s=1, i;
for (i = 1; i <= a; i++)
s *= i;
return s;
}

int main()
{
int x, y, i;
cout << "请输入颜色数量" << endl;
cin >> x;
cout << "请输入取出不同颜色球个数" << endl;
cin >> y;
i = jiecheng(x) / (jiecheng(y)*jiecheng(x-y));
cout << "有" << i << "种取法" << endl;

return 0;
}

 

 

posted @ 2018-03-20 17:14  KrnFx  阅读(112)  评论(1)    收藏  举报