【发布时间】:2016-09-06 12:44:59
【问题描述】:
我是 C 语言和编码的新手,我遇到了一个问题,要求我更改以下的函数头:
float RealRoot_1(float a, float b, float c);
float RealRoot_2(float a,float b,float c);
变成:
void RealRoot_1(void);
void RealRoot_2(void);
有人告诉我这与全局变量有关,但尝试了一段时间后我仍然无法弄清楚。谁能解释一下如何做?非常感谢。
源文件如下:
#include<stdio.h>
#include<math.h>
int main()
{
float RealRoot_1(float a, float b, float c); // Prototype declaration
float RealRoot_2(float a, float b, float c);
// Defining Input Variables
float x, y, z;
// Defining Output Variables
float Root_1, Root_2;
printf("Please enter the factor of X^2: ");
scanf("%f",&x);
printf("Please enter the factor of X: ");
scanf("%f",&y);
printf("Please enter the free factor: ");
scanf("%f",&z);
Root_1 = RealRoot_1(x,y,z);
Root_2 = RealRoot_2(x,y,z);
printf("the First Root is: %f \n", Root_1);
printf("the Second Root is: %f \n", Root_2);
system("pause");
}
float RealRoot_1(float a, float b, float c)
{
float x;
x = (-1*b + sqrt(pow(b,2) - 4 * a * c)) / (2 * a);
return x;
}
float RealRoot_2(float a, float b, float c)
{
float x;
x = (-1*b - sqrt(pow(b,2) - 4 * a * c)) / (2 * a);
return x;
}
【问题讨论】:
-
我不明白,这看起来是个很糟糕的主意。仅仅因为你可以做某事并不意味着你必须去做。
-
在 main() 之上声明原型。
-
这里必须同意@Sourav,我们在过去 40 年的大部分时间里都在朝着 more 封装方向发展。全局变量通常是个坏主意。所以,是的,它可以完成,但是,为了好的代码(并且为了避免我或我的孩子可能不得不维持这样的怪物),我不会告诉你如何:-)
-
@paxdiablo “全局变量通常是个坏主意。”我不知道谁教你这些东西,但对我来说,你听起来像是一个在暴民中的人,并且和其他人被教过同样的东西。全局变量有时可能是唯一的解决方案。
-
@machine_1,因此我使用了“一般”这个词。它们有自己的位置,还有多个返回点、
goto等等,但绝大多数代码应该避免使用它们。无论如何,我很难想出他们是唯一解决方案的场景。也许是最好的解决方案,但不是“唯一”。
标签: c function return global-variables void