• math.h应用, gcc test.c -o test -lm


    看个test.c中的代码:

    // 计算1 + 2 + 2^2 + 2^3 + 2^4 +... + 2^10的值
    
    #include <stdio.h>
    #include <math.h>
    #define UPPER 10
    #define BASE 2
    
    int main()
    {
        int i = 0;
        int sum = 0;
    
        while (i <= UPPER) {
            sum += pow(BASE, i);
            i++;
        }
        printf("sum is %d
    ", sum);
        return 0;
    }

    编译里,需要在gcc test.c -o test 增加 -lm

    即: gcc test.c -o test -lm来进行正确编译,不然出现如下错误:

    /tmp/ccLzpR0N.o: In function `main':
    test.c:(.text+0x34): undefined reference to `pow'
    collect2: error: ld returned 1 exit status

    上面是计算固定数的和;如果让用户输入数字来执行,可以加个scanf()函数,如下:

    // 计算1 + 2 + 2^2 + 2^3 + 2^4 +... + 2^n的值
    
    #include <stdio.h>
    #include <math.h>
    #define BASE 2
    
    int main()
    {
    
        int i = 0;
        float sum = 0.0;
        int n;
        printf("input your number: ");
        scanf("%d", &n);
        while (i <= n) {
            sum += pow(BASE, i);
            i++;
        }
        printf("sum = %f
    ", sum);
        return 0;
    }

    1.修改部分:

    float sum = 0.0;
    while (i <= n)
    printf("sum = %f
    ", sum);

    2.增加了

    printf("input your number: ");
    scanf("%d", &n);

    同样编辑时,使用: gcc test.c -o test -lm

    别忘记结尾的-lm

    下面看个实例: 

    // 计算1 + 1/2 + (1/2)^2 + (1/2)^3 + ... + (1/2)^n = ?
    #include <stdio.h>
    #include <math.h>
    #define BASE 1/2.0
    
    int main()
    {
    
        int i = 0;
        double sum = 0;
        int n;
        printf("input your number: ");
        scanf("%d", &n);
        for (i; i <= n; i++) {
            sum += pow(BASE, i);
        }
        printf("sum = %f
    ", sum);
        printf("sum = %.20f
    ", sum);
        return 0;
    }

    代码保存到test.c文件中,编译gcc test.c -lm

    执行 ./a.out

    输入10,

    运行结果为:

    sum = 1.999023
    sum = 1.99902343750000000000

    使用计算器,得到的准确结果为1.999023438;

    对比会发现程序运行得到的结果是存在误差的。

    参见文章:[浮点型数据]数值精度&取值范围 完全不同的概念 https://www.cnblogs.com/profesor/p/12750174.html

  • 相关阅读:
    解决IE9下JQuery的ajax失效的问题
    npm更新到最新版本的方法
    animate.css配合wow.min.js实现各种页面滚动效果
    Bootstrap导航点击菜单跳转与点击缩放菜单折叠按钮缓冲效果插件jquery.singlePageNav.min.js
    对json对象进行截取并按照某关键字进行排序
    巧用 position:absolute
    EasyUI Datagrid 分页
    Cssreset
    杂记
    for循环遍历json(附习题及答案)
  • 原文地址:https://www.cnblogs.com/profesor/p/12750565.html
Copyright © 2020-2023  润新知