-10

所以我正在尝试制作一个求解二次方程的 C 程序。我首先从头开始编写它,但它显示了相同的错误,所以我从一本 C 编程书籍中对其进行了一些更改。结果如下:

/*
Solves any quadratic formula.
*/
#include <stdio.h>
#include <math.h>

void main()
{
 float a, b, c, rt1= 0, rt2=0, discrim;
 clrscr();
 printf("Welcome to the Quadratic Equation Solver!");
 getch();
 printf("\nYour quadratic formula should be of the form a(x*x)+bx+c = 0");
 printf("\nPlease enter a\'s value:");
 scanf("%f", &a);
 printf("Great! Now enter b\'s value:");
 scanf("%f", &b);
 printf("One more to go! Enter c\'s value:");
 scanf("%f", &c);
 discrim = b*b - 4*a*c;
 if (discrim < 0)
  printf("\nThe roots are imaginary.");
 else
 {
  rt1 = (-b + sqrt(discrim)/(2.0*a);
  rt2 = (-b - sqrt(discrim)/(2.0*a);
  printf("\nThe roots have been calculated.");
  getch();
  printf("\nThe roots are:\nRoot 1:%f\nRoot 2:%f",rt1, rt2);
  getch();
  printf("\nThank you!");
  getch();
 }
}
4

4 回答 4

2

好吧,首先你有一些不匹配的括号:

 rt1 = (-b + sqrt(discrim)/(2.0*a);
 rt2 = (-b - sqrt(discrim)/(2.0*a);

您需要将这些行更改为:

 rt1 = (-b + sqrt(discrim))/(2.0*a);
 rt2 = (-b - sqrt(discrim))/(2.0*a);
                        ^^^^

您的编译器可能会给您这些行的错误消息,例如

foo.c:25: error: expected ‘)’ before ‘;’ token

仔细查看错误消息并研究第 25 行会告诉您缺少右括号。

于 2013-07-22T15:28:26.823 回答
2

你在这里错过了一些括号:

rt1 = (-b + sqrt(discrim)/(2.0*a);
rt2 = (-b - sqrt(discrim)/(2.0*a);

它应该如下所示:

rt1 = (-b + sqrt(discrim))/(2.0*a);
rt2 = (-b - sqrt(discrim))/(2.0*a);

您可以查看编译器警告。我的 (g++) 打印如下内容:

file.c:24:36: error: expected ‘)’ before ‘;’ token

24 是您应该检查错误的行号,而 36 是该行中的列号。

于 2013-07-22T15:31:39.467 回答
1
  rt1 = (-b + sqrt(discrim)/(2.0*a);
  rt2 = (-b - sqrt(discrim)/(2.0*a);
                          ^

您缺少正确的右括号。

于 2013-07-22T15:28:28.683 回答
1

如果您在 gcc 中编码,请使用以下代码并链接到数学库

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

int main()
{
 float a, b, c, rt1= 0, rt2=0, discrim;
 //clrscr();
 printf("Welcome to the Quadratic Equation Solver!");
 //getch();
 printf("\nYour quadratic formula should be of the form a(x*x)+bx+c = 0");
 printf("\nPlease enter a\'s value:");
 scanf("%f", &a);
 printf("Great! Now enter b\'s value:");
 scanf("%f", &b);
 printf("One more to go! Enter c\'s value:");
 scanf("%f", &c);
 discrim = b*b - 4*a*c;
 if (discrim < 0)
  printf("\nThe roots are imaginary.");
 else
 {
  rt1 = (-b + sqrt(discrim))/(2.0*a);
  rt2 = (-b - sqrt(discrim))/(2.0*a);
  printf("\nThe roots have been calculated.");
  // getch();
  printf("\nThe roots are:\nRoot 1:%f\nRoot 2:%f",rt1, rt2);
  // getch();
  printf("\nThank you!");
  //getch();
 }
}

并以这种方式编译

gcc example.c -o example -lm
于 2013-07-22T15:37:00.413 回答