2017-08-30 45 views
-1
#include<stdio.h> 
#include<math.h> 

int main() 
{ 
    double a,b,c,A,p, 
    scanf("%lf %lf %lf",&a,&b,&c); //Output is put in integers 

    p = (a+b+c)/2; 

    A = sqrt(p*(p-a)*(p-b)*(p-c)); 
    printf("Area of triangle is %lf",A); 
    //The output is coming out to be -nan for some inputs. 

    return 0;   
} 
+2

输入值?顺便说一句 - 总是检查'scanf'返回的值,即它返回3在你的情况? – 4386427

+3

您的输入是什么?你的预期产出是多少?你的实际产出是多少? ***作为文本***复制粘贴到问题主体中。另请[请阅读如何提出好问题](http://stackoverflow.com/help/how-to-ask)。我还建议您花一些时间阅读Eric Lippert的[如何调试小程序](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/),并学习如何使用调试器。 –

+1

查看['sqrt']的文档(http://en.cppreference.com/w/c/numeric/math/sqrt),发现该函数返回'nan'(不是数字)平方根无法计算,即负数。所以你的输入值可能会产生一个负数,你试图计算其平方根。虽然我只能猜测,因为你没有提供包括你的用户输入的[mcve]。 – muXXmit2X

回答

0
double a,b,c,A,p; 

你忘了; ?

如果你想给printf float或double您使用%F不会%LF

printf("Area of triangle is %f",A); 

您使用%LF只为一个浮动或双输入,输出使用%F

另一件事可能是sqrt()是负数。

+2

对于['printf'](http://en.cppreference.com/w/c/io/fprintf)格式''%lf“'和'”%f“'做同样的事情。 –

3

对于输入

1.0 2.0 5.0 

p = 4.0 
p - a = 3.0 
p - b = 2.0 
p - c = -1.0 // notice the sign 

所以你最终

sqrt(-24.0) // ups... sqrt of a negative number 

因此你-nan

也许你应该使用fabs摆脱负面价值。

BTW:nan表示 “不是一个数字” - 见https://en.wikipedia.org/wiki/NaN

BTW:经常检查由scanf返回的值,以确保它实际扫描预期的数值,即

if (scanf("%lf %lf %lf",&a,&b,&c) != 3) 
{ 
    // Input failure - add error handling... 
    // For instance: 
    printf("Illegal input - please provide 3 double as input\n"); 
    return -1; 
} 
+0

或者,也许OP想使用复数:['csqrt()'](http://en.cppreference.com/w/c/numeric/complex/csqrt):https://stackoverflow.com/a/9860772/8051589。但是我不这么认为,但是很好的答案!+1 –

+0

'晶圆厂'不能正常工作,正在生成与否定答案相同的答案(nan)。 – Barry

+0

@Barry - 听起来像你正在使用晶圆厂'不正确。尝试'A = sqrt(fabs(p *(pa)*(pb)*(pc)));' – 4386427