GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • 首页
  • HTML
  • JavaScript
  • CSS
  • React
  • Python3
  • Java
  • C
  • C++
  • C#
  • Go
  • SQL
  • Linux
  • VS Code

This view

  • Original page
  • New address

GeezerVison is showing www.runoob.com — C++ 数字 | 菜鸟教程

菜鸟教程 -- 学的不仅是技术,更是梦想!

  • Vue3 教程
  • Vue2 教程
  • Bootstrap3
  • Bootstrap4
  • Bootstrap5
  • 机器学习
  • PyTorch
  • TensorFlow
  • Sklearn
  • NLP
  • AI Agent
  • Ollama
  • Coding Plan
C++ 教程
C++ 教程 C++ 简介 C++ 环境设置 C++ 基本语法 C++ 注释 C++ 数据类型 C++ 变量类型 C++ 变量作用域 C++ 常量 C++ 修饰符类型 C++ 存储类 C++ 运算符 C++ 循环 C++ 判断 C++ 函数 C++ 数字 C++ 数组 C++ 字符串 C++ 指针 C++ 引用 C++ 日期 & 时间 C++ 基本的输入输出 C++ 结构体(struct) C++ vector 容器 C++ 数据结构

C++ 面向对象

C++ 类 & 对象 C++ 继承 C++ 重载运算符和重载函数 C++ 多态 C++ 数据抽象 C++ 数据封装 C++ 接口(抽象类)

C++ 高级教程

C++ 文件和流 C++ 异常处理 C++ 动态内存 C++ 命名空间 C++ 模板 C++ 预处理器 C++ 信号处理 C++ 多线程 C++ Web 编程

C++ 资源库

C++ STL 教程 C++ 导入标准库 C++ 标准库 C++ 有用的资源 C++ 实例 C++ 测验 C++ <iostream> C++ <fstream> C++ <sstream> C++ <iomanip> C++ <array> C++ <vector> C++ <list> C++ <forward_list> C++ <deque> C++ <stack> C++ <queue> C++ <priority_queue> C++ <set> C++ <unordered_set> C++ <map> C++ <unordered_map> C++ <bitset> C++ <algorithm> C++ <iterator> C++ <functional> C++ <numeric> C++ <complex> C++ <valarray> C++ <cmath> C++ <string> C++ <regex> C++ <ctime> C++ <chrono> C++ <thread> C++ <mutex> C++ <condition_variable> C++ <future> C++ <atomic> C++ <type_traits> C++ <typeinfo> C++ <exception> C++ <stdexcept> C++ <cstdio> C++ <cstdint> C++ <memory> C++ <new> C++ <utility> C++ <random> C++ <locale> C++ <codecvt> C++ <cassert> C++ <cwchar> C++ <climits> C++ <cfloat> C++ <cstdlib> C++ <numbers> C++ OpenCV
C++ 函数
C++ 数组

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++ 中一些有用的内置的数学函数。

为了利用这些函数,您需要引用数学头文件 <cmath>。

序号函数 & 描述
1double cos(double);
该函数返回弧度角(double 型)的余弦。
2double sin(double);
该函数返回弧度角(double 型)的正弦。
3double tan(double);
该函数返回弧度角(double 型)的正切。
4double log(double);
该函数返回参数的自然对数。
5double pow(double, double);
假设第一个参数为 x,第二个参数为 y,则该函数返回 x 的 y 次方。
6double hypot(double, double);
该函数返回两个参数的平方总和的平方根,也就是说,参数为一个直角三角形的两个直角边,函数会返回斜边的长度。
7double sqrt(double);
该函数返回参数的平方根。
8int abs(int);
该函数返回整数的绝对值。
9double fabs(double);
该函数返回任意一个浮点数的绝对值。
10double 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

C++ 数学常数

在 C++ 中,数学常数(如 π、e、黄金比例等)是许多算法和应用中不可或缺的部分,虽然早期版本的 C++ 中没有直接提供这些常数,但从 C++20 开始,标准库引入了几个常用的数学常数,并提供了更高效和统一的方式来访问它们。

更多内容参考:C++ 标准库 <numbers>。

π

  • 常量:std::numbers::pi
  • 类型:std::float32_t(32位浮动)、std::float64_t(64位浮动)

实例

#include <cmath>
#include <iostream>

int main() {
    std::cout << "pi: " << std::numbers::pi << std::endl;
}

自然对数的底数 e (Euler's Number)

  • 常量:std::numbers::e
  • 类型:std::float32_t、std::float64_t
std::cout << "e: " << std::numbers::e << std::endl;

黄金比例 φ (Golden Ratio)

  • 常量:std::numbers::phi
  • 类型:std::float32_t、std::float64_t
std::cout << "phi: " << std::numbers::phi << std::endl;

实例

#include <iostream>
#include <cmath>
#include <numbers>

int main() {
    std::cout << "pi: " << std::numbers::pi << std::endl;
    std::cout << "e: " << std::numbers::e << std::endl;
    std::cout << "phi: " << std::numbers::phi << std::endl;

    return 0;
}

输出结果为:

pi: 3.14159
e: 2.71828
phi: 1.61803
AI 思考中...
C++ 函数
C++ 数组

5 篇笔记 写笔记

  1. #0

       旭愿哥哥

      fan***[email protected]

      参考地址

    126

    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;
    }
    旭愿哥哥

       旭愿哥哥

      fan***[email protected]

      参考地址

    9年前 (2017-08-29)
  2. #0

       mokit

      zbi***[email protected]

      参考地址

    42

    关于 c++ 随机数的补充(取一定范围的随机数):

    可以在宏定义中顶一个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;
    }
    
    mokit

       mokit

      zbi***[email protected]

      参考地址

    9年前 (2017-10-26)
  3. #0

       抗寒抗旱抗倒伏

      180***[email protected]

    99

    补充说明:

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

    抗寒抗旱抗倒伏

       抗寒抗旱抗倒伏

      180***[email protected]

    8年前 (2018-08-24)
  4. #0

       adults

      223***[email protected]

    223

    使用随机数来发红包:

    #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(手气最佳)
    请按任意键继续. . .
    adults

       adults

      223***[email protected]

    8年前 (2018-11-01)
  5. #0

       是橡皮啊

      289***[email protected]

    50

    window下的RAND_MAX为:0x7fff=2^15-1=32767

    linxu下的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

    是橡皮啊

       是橡皮啊

      289***[email protected]

    7年前 (2020-04-13)

点我分享笔记

取消

  • 昵称 (必填)
  • 邮箱 (必填)
  • 引用地址
分类导航
  • Python / 数据科学
    • Python 教程
    • Python2.x 教程
    • FastAPI 教程
    • Flask 教程
    • Django 教程
    • NumPy 教程
    • Pandas 教程
    • SciPy 教程
    • Matplotlib 教程
    • Dash 教程
    • Jupyter Notebook 教程
    • Pillow 教程
    • 量化交易
    • R 教程
    • Julia 教程
  • AI / 智能开发
    • AI Agent(智能体)
    • AI(人工智能)
    • AI 应用案例
    • Codex 教程
    • Vibe Coding 教程
    • Claude Code
    • OpenCode
    • Skills(技能)
    • Ollama 教程
    • Hermes Agent
    • DeepSeek Harness
    • Pi Agent
    • AI 数学基础
    • TensorFlow 教程
    • PyTorch 教程
    • Scikit-learn 教程
    • 机器 教程
    • LangChain
    • 自然语言处理 NLP
    • OpenCV 教程
    • Selenium 教程
    • Playwright 教程
  • 前端开发
    • HTML 教程
    • HTML5 教程
    • CSS 教程
    • CSS3 教程
    • JavaScript 教程
    • HTML DOM 教程
    • TypeScript 教程
    • AJAX 教程
    • JSON 教程
    • Tailwind CSS 教程
    • Bootstrap4 教程
    • Bootstrap5 教程
    • Bootstrap6 教程
    • Foundation 教程
    • Vue.js 教程
    • Vue3 教程
    • React 教程
    • Next.js 教程
    • Three.js 教程
    • AngularJS 教程
    • Angular 教程
    • jQuery 教程
    • jQuery UI 教程
    • jQuery EasyUI 教程
    • ECharts 教程
    • Chart.js 教程
    • Highcharts 教程
    • Google 地图 教程
    • SVG 教程
    • Font Awesome 教程
  • 后端开发
    • Node.js 教程
    • Electron 教程
    • PHP 教程
    • Java 教程
    • Go 教程
    • Rust 教程
    • C# 教程
    • Unity 教程
    • Servlet 教程
    • JSP 教程
    • ASP 教程
    • AppML 教程
    • VBScript 教程
    • Swagger 教程
    • RESTful API 教程
    • Docker 教程
    • Linux 教程
    • ZooKeeper 教程
  • 数据库
    • SQL 教程
    • MySQL 教程
    • PostgreSQL 教程
    • SQLite 教程
    • MongoDB 教程
    • Redis 教程
    • Memcached 教程
  • 移动开发
    • Android 教程
    • Flutter 教程
    • Ionic 教程
    • jQuery Mobile 教程
    • Swift 教程
    • Kotlin 教程
  • DevOps / 工程化
    • Git 教程
    • SVN 教程
    • CMake 教程
    • Maven 教程
    • VS Code 教程
    • Obsidian 教程
    • PyCharm 教程
    • Eclipse 教程
    • Markdown 教程
    • LaTeX 教程
  • 编程语言
    • C 教程
    • C++ 教程
    • Zig 教程
    • Scala 教程
    • Ruby 教程
    • Perl 教程
    • Lua 教程
    • Dart 教程
    • 汇编语言 教程
    • Verilog 教程
  • 计算机基础
    • 计算机组成原理
    • 数据结构与算法
    • C 语言数据结构与算法
    • 设计模式
    • Python 设计模式
    • 正则表达式
    • HTTP 教程
    • TCP/IP 教程
    • 网络协议
    • W3C 教程
  • XML / Web Service
    • XML 教程
    • DTD 教程
    • XML DOM 教程
    • XSLT 教程
    • XPath 教程
    • XQuery 教程
    • XLink 教程
    • XPointer 教程
    • XML Schema 教程
    • XSL-FO 教程
    • Web Service 教程
    • WSDL 教程
    • SOAP 教程
    • RSS 教程
    • RDF 教程
  • .NET
    • ASP.NET 教程
    • MVC 教程
    • Razor 教程
    • Web Forms 教程
    • Web Pages 教程
    • PowerShell 教程
  • 网站建设
    • 网站建设指南
    • 浏览器信息
    • 网站主机教程
    • 网站品质

字节 Coding Plan 限时 9.9 元起,支持 Deepseek-V4、GLM-5.3、Doubao-Seed-Evolving、Kimi-K3。
百度 Dumate 百度推出的桌面级 AI 智能体。 输入激活码送 4000 积分
使用文档
Trae AI 原生开发环境,让编程更高效。新用户注册赠2500积分,管理项目,也交付成果。
Advertisement
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.