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

原文地址:https://www.cnblogs.com/profesor/p/12750565.html