2012-11-18 49 views
-7

我不知道如何将变量从main()传递给另一个函数。 我有这样的事情:如何将变量传递到另一个函数?

main() 
{ 
    float a, b, c; 

    printf("Enter the values of 'a','b' and 'c':"); 
    scanf("%f %f %f",&a,&b,&c); 
} 

double my_function(float a,float b,float c) 
{ 
    double d; 

     d=a+b+c 
     bla bla bla bla 

我如何传递一个,从主b和c,以创建my_function?现在程序停止在scanf()上并在我把值写入后直接结束。

我在这里看到了不同的例子,但他们没有帮到我很多。

+0

您应该在依赖具有新值的变量之前检查'scanf()'的返回值。 – unwind

+1

如果在'scanf'上停止,因为该函数等待输入完成。程序在'scanf'后退出,因为没有更多的语句可以执行。关于用参数调用一个函数,这就是你已经用'printf'和'scanf'完成的事情,只需用正确的参数调用你自己的函数即可。 –

回答

5

通过传递参数ab,并c只需调用该函数。语法:

retval = function_name(parameter1,parameter2,parameter3); //pass parameters as required 

像这样:

int main(void) 
{ 
    float a, b, c; 
    double d; 

    printf("Enter the values of 'a','b' and 'c': "); 
    if (scanf("%f %f %f",&a,&b,&c) == 3) 
    { 
     d = my_function(a, b, c); 
     printf("Result: %f\n", d); 
    } 
    else 
     printf("Oops: I didn't understand what you typed\n");  
} 
+0

这就是我所错过的。谢谢 – Zako

2

函数调用。

my_function(a, b, c); 
2

你必须从主调用函数!

float my_function(float a,float b,float c) 
{ 
    float d; 

    d=a+b+c; 
    return d ; 
} 

int main() 
{ 
    float a, b, c; 
    float result ; 

    printf("Enter the values of 'a','b' and 'c':"); 
    scanf("%f %f %f",&a,&b,&c); 

    result = my_function(a,b,c); 
    printf("\nResult is %f", result);  

    return 0; 
} 
+1

+1:工作很好。理想情况下,你会测试输入是否被正确接收。您的重写确保函数定义在使用之前处于范围内,并满足C99。我宁愿看到一个明确的'int main(void)'(至少C99需要'int')。 –

+0

很酷,很好的信息!编辑我的回复也是为了在main之前添加int。 – hack3r

相关问题