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