2016-10-04 65 views
0
#include <stdio.h> 
#include <math.h> 
int main(void) 
{ 
double a, b, c, root1, root2; 
printf("Input the coefficient a => "); 
scanf("%lf", &a); 
printf("Input the coefficient b => "); 
scanf("%lf", &b); 
printf("Input the coefficient c => "); 
scanf("%lf", &c); 
/* Compute the roots. */ 
root1 = (- b + sqrt(b*b-4*a*c))/(2*a); 
root2 = (- b - sqrt(b*b-4*a*c))/(2*a); 
printf("The first root is %8.3f\n", root1); 
printf("The second root is %8.3f\n", root2); 
return 0; 
} 

然而,我的输出是代码块不打印特定格式

Input the coefficient a => 232 
Input the coefficient b => 23 
Input the coefficient c => 2 
The first root is  nan 
The second root is  nan 

我只是一个初学者,是格式错误? 使用代码块,在C.

+4

负的平方根数字是'nan'。 – tkausl

+1

你期望输出什么? – mch

+0

我投票结束这个问题作为题外话题,因为它是一个数学问题,而不是编程问题。 – Lundin

回答

0

试试这个:

#include <stdio.h> 
#include <math.h> 

int main(void) 
{ 
double a, b, c, root1, root2; 
double temp; 
printf("Input the coefficient a => "); 
scanf("%lf", &a); 
printf("Input the coefficient b => "); 
scanf("%lf", &b); 
printf("Input the coefficient c => "); 
scanf("%lf", &c); 
/* Compute the roots. */ 
temp = b*b-4*a*c; 
if (temp >= 0) { 
    root1 = (- b + sqrt(temp))/(2*a); 
    root2 = (- b - sqrt(temp))/(2*a); 
    printf("The first root is %8.3f\n", root1); 
    printf("The second root is %8.3f\n", root2); 
} else { 
    printf("There is no root!\n"); 
} 

return 0; 
} 

记住:负荷数学库这样的 - > gcc的 “文件名” -lm

+3

请避免代码只回答,因为它并不直接表明变化是什么。相反地​​解释解决方案。 – user694733

+0

添加一个临时变量:double temp;然后temp = b * b-4 * a * c;然后检查它的价值是否定的否定的 –

+1

@ M.zanousi - 在答案中提供一些文字解释。请正确缩进代码。请检查'scanf'返回的值 – 4386427