我的sqrt()函数无效,我从命令行编译并追加-lm
/** initialize distance formula **/
double formula1 = (x2-x1) * 2 * 2;
double formula2 = (y2-y1) * 2 * 2;
double formula = formula1 + formula2;
/** call sqrt function to square root it **/
sqrt(formula);
printf("\n%lf", sqrt(formula));
return sqrt(formula);
我的输出答案是-nanSTUDENTID @ gio:〜$
在这里编辑我的完整代码,我道歉。
#include <stdio.h>
/** call math.h libbrary cause of sqrt() **/
#include <math.h>
/** define/declare constant **/
#define PI 3.14159
/** declaring prototypes **/
double distance(double x1, double x2, double y1, double y2);
double radius(double point1, double point2, double point3, double point4);
double circumference(double circle_circum);
double area(double circle_area);
/** declare pointer **/
void getXY(double *xPtr, double *yPtr);
int main (void) {
/** neither variables are initialized **/
double x;
double y;
/** variables are now initialized **/
getXY(&x, &y);
}
/** this function will prompt the user to enter x and y coordinates twice and then pass by reference to distance **/
void getXY(double *xPtr, double *yPtr) {
/** neither variables are initialized **/
double a;
double b;
/** variables are now initialized **/
*xPtr = a;
*yPtr = b;
printf("First, lets get the center of a circle. \nPlease enter the x and y coordinates, separated by a space: \n" );
scanf("%lf %lf", &a, &b);
/** neither variables are initialized **/
double c;
double d;
/** variables are now initialized **/
*xPtr = c;
*yPtr = d;
printf("Next, lets get a point on the circle \nPlease enter the x and y coordinates, separated by a space: \n");
scanf("%lf %lf", &c, &d);
/** call distance function **/
distance(a,b,c,d);
}
/** this function is gonna find this distance between two points **/
double distance(double x1, double x2, double y1, double y2) {
/** initialize distance formula **/
double formula1 = (x2-x1) * 2 * 2;
double formula2 = (y2-y1) * 2 * 2;
double formula = formula1 + formula2;
/** call sqrt function to square root it **/
sqrt(formula);
printf("\n%lf", sqrt(formula));
return sqrt(formula);
}
我正在路过让我们说1 0&amp; 0 0
答案 0 :(得分:3)
以下内容未将(x2 - x1)
提升至第二权力;相反,它乘以4:
double formula1 = (x2-x1) * 2 * 2;
下一行也是如此。
一旦你修复了这些,事情就会有所改善(你将不再尝试计算负数的实平方根,这就是给你NaN的原因。)
修改:要计算平方,请使用(x2-x1) * (x2-x1)
或pow(x2-x1, 2.0)
。
答案 1 :(得分:1)
你将把你的距离函数称为
distance (x1=1, x2=0, y1=0, y2=0)
然后
double formula1 = (x2-x1) * 2 * 2;
将评估为-4
然后
double formula = formula1 + formula2;
将评估为-4
从而
sqrt(formula);
as -nan