Cpp class exercise 4:修订间差异
跳转到导航
跳转到搜索
无编辑摘要 |
无编辑摘要 |
||
| 第1行: | 第1行: | ||
{{DISPLAYTITLE: “C++ 编程入门班” 练习四}} | {{DISPLAYTITLE: “C++ 编程入门班” 练习四}} | ||
== 预习练习 == | |||
【例4-1】数组的定义、赋值和遍历 | |||
<syntaxhighlight lang="C++" line> | |||
#include <iostream> | |||
using namespace std; | |||
int main() | |||
{ | |||
int a[3]; //定义数组 | |||
a[0]= 1; //通过索引引用,并赋值。注意索引是从0开始的。 | |||
a[1]= 2; | |||
a[2]= 3; | |||
int b[3]= {5,6,7}; //定义数组并同时赋值。注意括号是花括号。 | |||
for(int i=0;i<3;i++) | |||
{ | |||
cout << a[i] << endl; | |||
} | |||
//计算数组b的长度,为什么要用这种方法呢? | |||
//如果改成 int lenth = sizeof(b); | |||
// lenth的值会是多少呢? | |||
int lenth = sizeof(b)/sizeof(int); | |||
for(int i=0;i<lenth;i++) | |||
{ | |||
cout << b[i] << endl; | |||
} | |||
return 0; | |||
} | |||
</syntaxhighlight> | |||
【例4-2】冒泡排序法 | |||
<syntaxhighlight lang="C++" line> | |||
#include <iostream> | |||
#include <stdlib.h> | |||
#include <time.h> | |||
#define random(x) (rand()%x) | |||
using namespace std; | |||
int main() | |||
{ | |||
int a[10]; | |||
srand((int)time(0));//用系统时间来做种子 | |||
for(int i=0;i<10;i++) | |||
{ | |||
a[i] = random(100); // 取100以内的随机数 | |||
} | |||
//原始顺序 | |||
for(int i=0;i<10;i++) | |||
{ | |||
cout << a[i] << ","; // 逐个输出 | |||
} | |||
cout << endl; | |||
for(int i=0;i<10;i++) | |||
{ | |||
for(int j=i+1;j<10;j++) | |||
{ | |||
if(a[i]>a[j]) | |||
{ | |||
//交换 | |||
int temp = a[i]; | |||
a[i] = a[j]; | |||
a[j] = temp; | |||
} | |||
} | |||
} | |||
//排序以后的顺序 | |||
for(int i=0;i<10;i++) | |||
{ | |||
cout << a[i] << ","; // 逐个输出 | |||
} | |||
cout << endl; | |||
return 0; | |||
} | |||
</syntaxhighlight> | |||
2019年5月17日 (五) 20:09的版本
预习练习
【例4-1】数组的定义、赋值和遍历
#include <iostream>
using namespace std;
int main()
{
int a[3]; //定义数组
a[0]= 1; //通过索引引用,并赋值。注意索引是从0开始的。
a[1]= 2;
a[2]= 3;
int b[3]= {5,6,7}; //定义数组并同时赋值。注意括号是花括号。
for(int i=0;i<3;i++)
{
cout << a[i] << endl;
}
//计算数组b的长度,为什么要用这种方法呢?
//如果改成 int lenth = sizeof(b);
// lenth的值会是多少呢?
int lenth = sizeof(b)/sizeof(int);
for(int i=0;i<lenth;i++)
{
cout << b[i] << endl;
}
return 0;
}
【例4-2】冒泡排序法
#include <iostream>
#include <stdlib.h>
#include <time.h>
#define random(x) (rand()%x)
using namespace std;
int main()
{
int a[10];
srand((int)time(0));//用系统时间来做种子
for(int i=0;i<10;i++)
{
a[i] = random(100); // 取100以内的随机数
}
//原始顺序
for(int i=0;i<10;i++)
{
cout << a[i] << ","; // 逐个输出
}
cout << endl;
for(int i=0;i<10;i++)
{
for(int j=i+1;j<10;j++)
{
if(a[i]>a[j])
{
//交换
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
//排序以后的顺序
for(int i=0;i<10;i++)
{
cout << a[i] << ","; // 逐个输出
}
cout << endl;
return 0;
}