0
我使用二次公式找到函数根的程序如下。它完美的作品。但是,如果不在全球范围内定义三个变量,我就无法实现它。根据我的项目描述,我不应该这样做。局部变量的全局变量
有关如何在本地定义它们以及在打印结果函数能够这样做之前计算不会丢失的任何建议或更改?
#include <stdio.h>
#include <math.h>
double discriminant;
double root_one = 0, root_two = 0;
double a = 0, b = 0, c = 0;
int checkComplex(double a, double b, double c)
{
discriminant = (b * b) - 4 * (a * c);
if (discriminant == 0)
return 2;
else if (discriminant > 0)
return 1;
else
return 0;
}// end checkComplex
void calculateRoots(double a, double b, double c)
{
root_one = (-b + sqrt(discriminant))/(2 * a);
root_two = (-b - sqrt(discriminant))/(2 * a);
} // end calculateRoots
void getData()
{
printf("Enter a: ");
scanf("%lf", &a);
printf("\nEnter b: ");
scanf("%lf", &b);
printf("\nEnter c: ");
scanf("%lf", &c);
}// end getData
void printResults()
{
if (checkComplex(a, b, c) == 1)
{
calculateRoots(a, b, c);
printf("\n\n-----------------------------------------\n");
printf("\nThe quantity (b^2-4ac) is %.2lf", discriminant);
printf("\n\nfirst root = %.2lf\nsecond root = %.2lf\n\n", root_one,
root_two);
}// if discriminant is 1
else if (checkComplex(a, b, c) == 0)
{
printf("\n\n-----------------------------------------\n");
printf("The discriminant (b^2-4ac) is negative (imaginary)");
printf("\nTherefore, the roots are complex\n");
} // if discriminant is 0
else if (checkComplex(a == 2, b == 2, c == 2))
{
calculateRoots(a, b, c);
printf("\n\n-----------------------------------------\n");
printf("\nThe quantity (b^2-4ac) is %.2lf", discriminant);
printf("\n\nfirst root = %.2lf\nsecond root = %.2lf\n\n", root_one,
root_two);
}// if discriminant is greater than 1
} // end printResults
int main()
{
getData();
printResults();
return 0;
} // End program
在main中定义它们,然后通过引用而不是按值传递。 –
'checkComplex(a == 2,b == 2,c == 2)'.... huh? – ikegami
可能重复的[调用程序中看不到的变量变量?](https://stackoverflow.com/questions/27320240/variable-changed-in-function-not-seen-by-caller) – Sebivor