//5-4-1
//随机生成求和平均值
#include <stdio.h>
#include <stdlib.h>
#include <time.h> //时间的头文件
void main()
{
time_t ts; //创建一个时间的变量
//设置随机数种子
srand((unsigned int)time(&ts)); //调用一个srand()函数,在time函数中取ts的地址对其初始化,然后强制转换无符号整型
int a[10];
for (int i = 0; i < 10; i++)
{
a[i] = rand() % 100; //随机生成0-99之间的随机数(0-99之间的数字除以100 )
printf("\n%d,%x", a[i], &a[i]);
}
int all = 0;
double total = 0.0;
for (int i = 0; i < 10; i++)
{
all += a[i];
}
total = all;
total /= 10;
printf("\n和=%d,平均值=%f", all, total);
system("pause");
}
//5-4-2
//查找一个元素
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void main()
{
time_t ts;
srand((unsigned int)time(&ts)); //设置随机数种子
int a[10];
for (int i = 0; i < 10; i++)
{
a[i] = rand() % 100;
printf("\n%d,%x", a[i], &a[i]);
}
int num;
int flag = 0; //设置一个标志位,假设开始没照到
scanf_s("%d", &num); //不是用vs2013可以把_s去掉
for (int i = 0; i < 10; i++)
{
if (num == a[i])
{
flag = 1;
break;
}
}
if (flag == 1)
{
printf("找到");
}
else
{
printf("没找到");
}
system("pause");
}
//5-4-3
//斐波那契数列
//1 1 2 3 5 8 13 21 即:从第三个数字开始依次等于前两个数字之和
#include <stdio.h>
#include <stdlib.h>
void main()
{
int a[10];
a[0] = 1;
a[1] = 1;
for (int i = 2; i < 10; i++)
{
a[i] = a[i - 1] + a[i - 2]; //向前移动
}
for (int i = 0; i < 10; i++)
{
printf("\na[%d]=%d", i, a[i]);
}
system("pause");
}
//5-4-4
//求一个随机数最大值
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void main()
{
time_t ts;
srand((unsigned int)time(&ts)); //设置随机数种子
int a[10];
for (int i = 0; i < 10; i++)
{
a[i] = rand() % 100;
printf("\n%d", a[i]);
}
int max = a[0]; //假定第一个元素是最大值
int max1 = 0; //记录初始下标为0
for (int i = 1; i < 10; i++)
{
if (a[i]>max) //如果后一个元素大于 假定的max值,则交换两个数字
{
max = a[i];
max1 = i;
}
}
printf("\n最大值%d,下标为%d", max, max1);
system("pause");
}