所以我试图制作一个解决二次方程的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();
}
}
答案 0 :(得分: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行会告诉您缺少右括号。
答案 1 :(得分: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是此行中的列号。
答案 2 :(得分:1)
rt1 = (-b + sqrt(discrim)/(2.0*a);
rt2 = (-b - sqrt(discrim)/(2.0*a);
^
你错过了正确的右括号。
答案 3 :(得分: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