C 中的平方根程序未编译
Square Root Program in C not Compiling
刚开始学C,在C教程网站上找到这个例子程序,编译时报错
这是程序,根据用户输入计算数字的平方根:
#include <stdio.h>
#include <math.h>
int main()
{
double num, root;
/* Input a number from user */
printf("Enter any number to find square root: ");
scanf("%lf", &num);
/* Calculate square root of num */
root = sqrt(num);
/* Print the resultant value */
printf("Square root of %.2lf = %.2lf", num, root);
return 0;
}
我在Ubuntu中使用gcc
编译它:
gcc -o square_root square_root.c
这里是错误:
/tmp/cc9Z3NCn.o: In function `main':
square_root.c:(.text+0x4e): undefined reference to `sqrt'
collect2: error: ld returned 1 exit status
我做错了什么?我可以看到导入了数学模块,为什么会报错?
再说一遍,今天刚开始学C,就是想弄清楚怎么把程序弄到运行。感谢您的耐心等待,因为它一定是显而易见的。
sqrt
存在于数学库中,因此您需要使用 -lm
:
告诉您的程序 link 到它
gcc -o square_root square_root.c -lm
你需要用-lm标志编译它
gcc -o square_root square_root.c -lm
刚开始学C,在C教程网站上找到这个例子程序,编译时报错
这是程序,根据用户输入计算数字的平方根:
#include <stdio.h>
#include <math.h>
int main()
{
double num, root;
/* Input a number from user */
printf("Enter any number to find square root: ");
scanf("%lf", &num);
/* Calculate square root of num */
root = sqrt(num);
/* Print the resultant value */
printf("Square root of %.2lf = %.2lf", num, root);
return 0;
}
我在Ubuntu中使用gcc
编译它:
gcc -o square_root square_root.c
这里是错误:
/tmp/cc9Z3NCn.o: In function `main':
square_root.c:(.text+0x4e): undefined reference to `sqrt'
collect2: error: ld returned 1 exit status
我做错了什么?我可以看到导入了数学模块,为什么会报错?
再说一遍,今天刚开始学C,就是想弄清楚怎么把程序弄到运行。感谢您的耐心等待,因为它一定是显而易见的。
sqrt
存在于数学库中,因此您需要使用 -lm
:
gcc -o square_root square_root.c -lm
你需要用-lm标志编译它
gcc -o square_root square_root.c -lm