1.rand()函数
rand()函数可以产生伪随机数,因为rand()函数的实现采用的是线性同余法,并不是真正的随机数,只是因为其周期长,所以在一定范围内可以认为是随机的,所以每次运行产生的数字都是一样。为了让rand()函数产生真正意义上的随机数,可以使用srand()函数产生rand()产生随机数时的随机数种子。
srand()函数的用法如下:
srand(seed)
其中seed必须是一个整数,而且可以使用rime(0)的返回值当做seed。time()函数返回当前时间,包含在头文件time.h中。
【应用举例】利用计算机随机出一道100以内的加减法,根据用户的答案给出Right或Wrong的提示。
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stdio.h>
//判断加减法正确性
int main()
{
int opr; //opr代表运算符
int a, b, c; //a、b代表操作数,c代表运算结果
srand(time(0));
opr = rand() % 100;
a = rand() % 10;
b = rand() % 10;
if(opr%2==0)
{
printf("%d+%d=", a, b);
scanf("%d", &c);
if (a + b == c)
printf("Right!\n");
else
printf("Wrong!\n");
}
else
{
printf("%d-%d=", a, b);
scanf("%d", &c);
if (a - b == c)
printf("Right!\n");
else
printf("Wrong!\n");
}
return 0;
}
2.求最大公约数
求最大公约数的方法有两种:辗转相除法和穷举法。感觉穷举法更简单?
【辗转相除法】
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stdio.h>
//求任意两个正整数的最大公约数和最小公倍数
int main()
{
int m, n, r, t;
int x, y;
printf("please input the number : m & n");
scanf("%d %d", &m, &n);
if(m<n)
{
t = m;
m = n;
n = t;
}
x = m;
y = n;
r = m % n;
while(r>0)
{
m = n;
n = r;
r = m % n;
}
printf("The greatest common divisor is %d\n", n);
printf("The least common multiple is %d\n", x * y / n);
return 0;
}
【穷举法】
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stdio.h>
//用穷举法求任意两个正整数的最大公约数和最小公倍数
int main()
{
int m, n, t;
printf("please input the number m & n :");
scanf("%d %d", &m, &n);
if (m > n)
t = n;
else
t = m;
while (t >1)
{
if (m % t == 0 && n % t == 0)
break;
t--;
}
printf("The greatest common divisor is %d\n", t);
printf("The least common multiple is %d\n", m * n / t);
return 0;
}