最近正在跟著一本書——《第五版資訊學奧賽一本通(C++版)》學習C++,書后有一道題如下:
【題目描述】
利用公式x1=?b+b2?4ac√2a,x2=?b?b2?4ac√2a,求一元二次方程ax2+bx+c=0的根,其中a不等于0。結果要求精確到小數點后5位。
【輸入】
輸入一行,包含三個浮點數a,b,c(它們之間以一個空格分開),分別表示方程ax2+bx+c=0的系數。
【輸出】
輸出一行,表示方程的解。
若兩個實根相等,則輸出形式為:“x1=x2=...”;
若兩個實根不等,在滿足根小者在前的原則,則輸出形式為:“x1=...;x2=...“;
若無實根輸出“No answer!”。
所有輸出部分要求精確到小數點后5位,數字、符號之間沒有空格。
【輸入樣例】
-15.97 19.69 12.02
【輸出樣例】
x1=-0.44781;x2=1.68075
我的程式如下:
# include <cstdio>
# include <cmath>
using namespace std;
int main()
{
double a, b, c, sqrtn, x1, x2; //創建abc常數,
scanf("%lf %lf %lf", &a, &b, &c);
sqrtn = (b * b) - (4 * a * c);
if (sqrtn < 0)
{
printf("%s", "No answer!");
}
else
{
x1 = (sqrt(sqrtn) - b) / (2 * a);
x2 = ((-b) - sqrt(sqrtn)) / (2 * a);
if (x1 == x2)
{
printf("%s%.5lf", "x1=x2=", x1);
}
else
{
if (x1 < x2)
{
printf("%s%.5lf%s%.5lf", "x1=", x1, ";x2=", x2);
}
else
{
printf("%s%.5lf%s%.5lf", "x1=", x2, ";x2=", x1);
}
}
}
return 0;
}
那本書有一個配套的測評網站http://ybt.ssoier.cn:8088/,我把我的程式傳上去之后它用十組數測驗了十遍,其他九變都對了,就有一組數它說答案錯誤,我也不能看到我到底哪里錯了,回頭又看了代碼很迷茫

,在此請教各位大神!望各位大佬們回答,感謝!!!感謝!!!
uj5u.com熱心網友回復:
供參考://【輸入樣例】
//-2 5 0
//【輸出樣例】
//x1=-0.00000 x2=2.50000
# include <cstdio>
# include <cmath>
using namespace std;
int main()
{
double a, b, c, sqrtn, x1, x2;//創建abc常數,
scanf("%lf %lf %lf", &a, &b, &c);
if(a==0)return -1;
sqrtn = (b * b) - (4 * a * c);
if (sqrtn < 0)
{
printf("%s", "No answer!");
}
if(sqrtn == 0)
{
printf("%s%.5lf", "x1=x2=", (-b)/(2*a)+0.0000001);////防止輸出-0.00的情況
}
if(sqrtn > 0)
{
x1 = (sqrt(sqrtn) - b) / (2 * a)+ 0.0000001;
x2 = ((-b) - sqrt(sqrtn)) / (2 * a)+0.0000001;
if (x1 < x2)
{
printf("%s%.5lf%s%.5lf", "x1=", x1, ";x2=", x2);
}
else
{
printf("%s%.5lf%s%.5lf", "x1=", x2, ";x2=", x1);
}
}
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/257227.html
標籤:C++ 語言
