2016-11-30 179 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

谢谢,我会考虑您的观点并尝试改进我的工作。 –