2016-11-30 145 views
0

我對編程和編碼非常陌生,所以我遇到了一些我似乎無法理解的問題。我真的找到答案,但徒勞無功。之前 '{' 令牌編譯器錯誤初學者問題

;

預期 '':

編譯器中提到2個錯誤:

在函數 'intmain()'

#include<iostream> 
#include<math.h> 
using namespace std; 
main() 
{ 
    float a, b, c, D, x1, x2, x; 
    cout<<"enter the value of a :"; 
    cin>>a; 
    cout<<"enter the value of b :"; 
    cin>>b; 
    cout<<"enter the value of c :"; 
    cin>>c; 
    D= b*b-4*a*c; 
    if(D>0) 
    { 
    x1= (-b-sqrt(D))/(2*a); 
    x2= (-b+sqrt(D))/(2*a); 
    cout<<"the roots of the equation are"<<x1<<"and"<<x2<<" \n"; 
    } 
    else if (D=0) 
    {x= -b/(2*a); 
    cout<<"the double root of the equation is"<<x<<" \n"; 
    } 
    else (D<0) 
    { 
    cout<<"no solution \n:"; 
    } 
    system("pause") ; 
    } 

回答

3

我正在回答這個問題,因爲它可能是完全破碎的代碼的典型案例。這裏是錯誤:

using namespace std; < - 一個人不應該這樣做。

main() < - 原型爲mainint main()int main(int, char* [])

float a, b, c, D, x1, x2, x; < - 在聲明所有變量 '提前' 的習慣沒有得到。相反,當你需要他們的時候宣佈他們。

else if (D=0) < ---這不是你想要做的。您分配了0做D.您想比較它們,所以請使用if (D == 0)

else (D<0) < - 缺少if。應該是else if (D < 0)

{x= -b/(2*a); < - 這只是一個可怕的風格。除非身體是一條線,否則不要在打開大括號後放置其他語句,並且在這種情況下在同一行中關閉大括號。

而且無處不在 - 正確地格式化您的代碼,就像文本一樣。

+0

謝謝你的幫助。我將通過使用您提供的解決方案解決問題。 –

0

它在這裏:

else (D<0) 

編譯器是不高興,因爲它需要一個身體爲else,和你沒有提供的。

語法

if (condition) 
{ 

} 
else 
{ 

} 

你不需要告訴編譯器的「其他」條件是什麼;這是condition是錯誤的。

+0

謝謝,我會考慮您的觀點並嘗試改進我的工作。 –