2016-10-04 81 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