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++库 内置数学函数

需要引用数学头文件 <cmath>

 三、随机数

关于随机数生成器,有两个相关的函数。一个是 rand(),该函数只返回一个伪随机数。生成随机数之前必须先调用 srand() 函数

#include <iostream>
#include <ctime>
#include <cstdlib>
 
using namespace std;
 
int main ()
{
   int i,j;
 
   // 设置种子
   srand( (unsigned)time( NULL ) );      //使用 time() 函数 获取 系统时间的秒数  ,作为随机数种子   再调用 rand() 生成 随机数
/* 生成 10 个随机数 */
   for( i = 0; i < 10; i++ )
   {
      // 生成实际的随机数
      j= rand();
      cout <<"随机数: " << j << endl;
   }
 
   return 0;
}

结果:

随机数: 1748144778

随机数: 630873888

。。。

补充:

1.

 2.取一定范围的随机数

#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;
}

 3.

(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()%[区间内数的个数]+[区间起点值])

原文地址:https://www.cnblogs.com/expedition/p/11319911.html