C++ 数字
通常,当我们需要用到数字时,我们会使用原始的数据类型,如 int、short、long、float 和 double 等等。这些用于数字的数据类型,其可能的值和数值范围,我们已经在 C++ 数据类型一章中讨论过。
C++ 定义数字
我们已经在之前章节的各种实例中定义过数字。下面是一个 C++ 中定义各种类型数字的综合实例:
#include <iostream>
using namespace std;
int main ()
{
// 数字定义
short s;
int i;
long l;
float f;
double d;
// 数字赋值
s = 10;
i = 1000;
l = 1000000;
f = 230.47;
d = 30949.374;
// 数字输出
cout << "short s :" << s << endl;
cout << "int i :" << i << endl;
cout << "long l :" << l << endl;
cout << "float f :" << f << endl;
cout << "double d :" << d << endl;
return 0;
}
当上面的代码被编译和执行时,它会产生下列结果:
short s :10
int i :1000
long l :1000000
float f :230.47
double d :30949.4
C++ 数学运算
在 C++ 中,除了可以创建各种函数,还包含了各种有用的函数供您使用。这些函数写在标准 C 和 C++ 库中,叫做内置函数。您可以在程序中引用这些函数。
C++ 内置了丰富的数学函数,可对各种数字进行运算。下表列出了 C++ 中一些有用的内置的数学函数。
为了利用这些函数,您需要引用数学头文件 。
序号 | 函数 | 描述 |
---|---|---|
1 | double cos(double); | 该函数返回弧度角(double 型)的余弦。 |
2 | double sin(double); | 该函数返回弧度角(double 型)的正弦。 |
3 | double tan(double); | 该函数返回弧度角(double 型)的正切。 |
4 | double log(double);` | 该函数返回参数的自然对数。 |
5 | double pow(double, double); | 假设第一个参数为 x,第二个参数为 y,则该函数返回 x 的 y 次方。 |
6 | double hypot(double, double); | 该函数返回两个参数的平方总和的平方根,也就是说,参数为一个直角三角形的两个直角边,函数会返回斜边的长度。 |
7 | double sqrt(double); | 该函数返回参数的平方根。 |
8 | int abs(int); | 该函数返回整数的绝对值。 |
9 | double fabs(double); | 该函数返回任意一个浮点数的绝对值。 |
10 | double floor(double); | 该函数返回一个小于或等于传入参数的最大整数。 |
下面是一个关于数学运算的简单实例:
#include <iostream>
#include <cmath>
using namespace std;
int main ()
{
// 数字定义
short s = 10;
int i = -1000;
long l = 100000;
float f = 230.47;
double d = 200.374;
// 数学运算
cout << "sin(d) :" << sin(d) << endl;
cout << "abs(i) :" << abs(i) << endl;
cout << "floor(d) :" << floor(d) << endl;
cout << "sqrt(f) :" << sqrt(f) << endl;
cout << "pow( d, 2) :" << pow(d, 2) << endl;
return 0;
}
当上面的代码被编译和执行时,它会产生下列结果:
sin(d) :-0.634939
abs(i) :1000
floor(d) :200
sqrt(f) :15.1812
pow( d, 2 ) :40149.7
C++ 随机数
在许多情况下,需要生成随机数。关于随机数生成器,有两个相关的函数。一个是 rand(),该函数只返回一个伪随机数。生成随机数之前必须先调用 srand() 函数。
下面是一个关于生成随机数的简单实例。实例中使用了 time() 函数来获取系统时间的秒数,通过调用 rand() 函数来生成随机数:
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main ()
{
int i,j;
// 设置种子
srand( (unsigned)time( NULL ) );
/* 生成 10 个随机数 */
for( i = 0; i < 10; i++ )
{
// 生成实际的随机数
j= rand();
cout <<"随机数: " << j << endl;
}
return 0;
}
当上面的代码被编译和执行时,它会产生下列结果:
随机数: 1748144778
随机数: 630873888
随机数: 2134540646
随机数: 219404170
随机数: 902129458
随机数: 920445370
随机数: 1319072661
随机数: 257938873
随机数: 1256201101
随机数: 580322989
window和linux下的RAND_MAX
window下的RAND_MAX为:0x7fff=2^15-1=32767
linux下的RAND_MAX为:2^31-1=2147483647
不妨,就Windows下进行说明:
Rand函数返回返回值是0到RAND_MAX(32767) 范围内的一个(伪)随机整数。
取指定区间的(伪)随机数不建议采用“模除+加法”的方式,
譬如:如果采用此法去0-10000内的随机数,则写法为
srand( (unsigned)time( NULL ) );
int n = rand()%10000;
则0-2767之间每个数出现的概率为4/32676,而2768-9999之间的书出现的概率为3/32676,和前者是不同的。不过rand()产生的是伪随机数了这个无关紧要,哈哈哈 。
建议采用如下方式:
int u = (double)rand() / (RAND_MAX + 1) * (range_max - range_min)+ range_min
一下是VS开发文档示例:
// crt_rand.c
// This program seeds the random-number generator
// with the time, then exercises the rand function.
//
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
void SimpleRandDemo( int n )
{
// Print n random numbers.
int i;
for( i = 0; i < n; i++ )
printf( " %6d\n", rand() );
}
void RangedRandDemo( int range_min, int range_max, int n )
{
// Generate random numbers in the half-closed interval
// [range_min, range_max). In other words,
// range_min <= random number < range_max
int i;
for ( i = 0; i < n; i++ )
{
int u = (double)rand() / (RAND_MAX + 1) * (range_max - range_min)
+ range_min;
printf( " %6d\n", u);
}
}
int main( void )
{
// Seed the random-number generator with the current time so that
// the numbers will be different every time we run.
srand( (unsigned)time( NULL ) );
SimpleRandDemo( 10 );
printf("\n");
RangedRandDemo( -100, 100, 10 );
}
建议使用random库生成真随机数,如下:
#include <random>
#include <iostream>
using namespace std;
int main()
{
random_device rd; // non-deterministic generator
mt19937 gen(rd()); // to seed mersenne twister.
uniform_int_distribution<> dist(1,6); // distribute results between 1 and 6 inclusive.
for (int i = 0; i < 5; ++i) {
cout << dist(gen) << " "; // pass the generator to the distribution.
}
cout << endl;
}
输出如下:
5 1 6 1 2
链接1: https://docs.microsoft.com/zh-cn/cpp/standard-library/random?view=vs-2019.
链接2: https://docs.microsoft.com/zh-cn/cpp/c-runtime-library/reference/rand?view=vs-2019.
取一定范围的随机数
1、rand 随机数产生的范围
在标准的 C 库中函数 rand() 可以生成 0~RAND_MAX 之间的一个随机数,其中 RAND_MAX 是 stdlib.h 中定义的一个整数,它与系统有关,至少为 32767。
2、使用 rand() 和 srand() 产生指定范围内的随机整数的方法
“模除+加法”的方法。如要产生 [m,n] 范围内的随机数 num,可用:int num=rand()%(n-m+1)+m;(即 rand()%[区间内数的个数]+[区间起点值])
可以在宏定义中顶一个random(int number)函数:
#include <iostream>
#include<stdio.h>
#include<time.h>
#define random(x)(rand()%x)
using namespace std;
int main()
{
srand((int)time(0));//部署随机种子
for (int i = 0; i < 10; i++){
cout << random(100) << endl;
//输出0-100的随机数
};
return 0;
}
例子
使用随机数来发红包:
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <iomanip>
#include <math.h>
using namespace std;
int main()
{
int i, number;
int best;//手气最佳
float total;
cout << "请输入红包金额:";
cin >> total;
cout << "请输入抢红包人数:";
cin >> number;
/* 生成随机数 */
// 设置种子
srand((unsigned)time(NULL));
float a[1024];//保存每个人的随机数。最多支持1024个人抢红包。
float b[1024];//保存每个人获得的红包金额。
float suma = 0;//随机数总和。
float sumb = 0;//红包总和。
int max = 0;
for (i = 0; i < number; i++)
{
// 生成实际的随机数
a[i] = rand() % 100;
if (a[i] > max){
max = a[i];
best = i;//获取手气最佳
}
suma += a[i];
}
for (i = 0; i < number - 1; i++)
{
b[i] = a[i] / suma * total;//按照随机数计算每个人实际获得的金额
sumb += round(b[i] * 100) / 100.0;//将红包金额保留两位小数
//输出信息
cout << "第" << setiosflags(ios::right)<< setw(3) << i + 1 <<
"个人的红包是:" << setiosflags(ios::right) << setw(6) <<
setiosflags(ios::fixed) << setprecision(2) <<
round(b[i] * 100) / 100.0 ;
if (best == i){
cout << "(手气最佳)" << endl;
}
else {
cout << endl;
}
}
//最后一人的红包金额等于总金额减去前面的金额。
cout << "第" << setiosflags(ios::right)<<
setw(3) << number << "个人的红包是:" <<
setiosflags(ios::right) << setw(6) << setiosflags(ios::fixed) <<
setprecision(2) << round((total - sumb) * 100) / 100.0;
if (best == number - 1){
cout << "(手气最佳)" << endl;
}
else {
cout << endl;
}
return 0;
}
结果:
请输入红包金额:100
请输入抢红包人数:10
第 1个人的红包是: 0.38
第 2个人的红包是: 3.06
第 3个人的红包是: 11.66
第 4个人的红包是: 4.40
第 5个人的红包是: 17.02
第 6个人的红包是: 14.53
第 7个人的红包是: 6.12
第 8个人的红包是: 13.19
第 9个人的红包是: 11.85
第 10个人的红包是: 17.79(手气最佳)
请按任意键继续. . .
srand函数
srand函数是随机数发生器的初始化函数。
原型: void srand(unsigned seed);
用法:它需要提供一个种子,这个种子会对应一个随机数,如果使用相同的种子后面的rand()函数会出现一样的随机数。如: srand(1); 直接使用 1 来初始化种子。不过为了防止随机数每次重复,常常使用系统时间来初始化,即使用 time 函数来获得系统时间,它的返回值为从 00:00:00 GMT, January 1, 1970 到现在所持续的秒数,然后将 time_t 型数据转化为(unsigned)型再传给 srand 函数,即: srand((unsigned) time(&t)); 还有一个经常用法,不需要定义time_t型t变量,即: srand((unsigned) time(NULL)); 直接传入一个空指针,因为你的程序中往往并不需要经过参数获得的t数据。
例子:
#include <stdlib.h>
#include <stdio.h>
#include <time.h> /*用到了time函数,所以要有这个头文件*/
#define MAX 10
int main( void)
{
int number[MAX] = {0};
int i;
srand((unsigned) time(NULL)); /*播种子*/
for(i = 0; i < MAX; i++)
{
number[i] = rand() % 100; /*产生100以内的随机整数*/
printf("%d ", number[i]);
}
printf("\n");
return 0;
}