如何将float变量从一个函数传递给其他函数。

时间:2015-04-18 09:42:29

标签: c variables local

我正在做一个程序,我必须在其他函数中使用局部变量。如果变量数据类型是int但是如果它是float,那么我能够这样做,但它不起作用。

我使用以下代码传递int:

的值
int func1()
{
    float a = 2.34, b = 3.45, res1;
    int c = 2, d = 3, res2;
    res1 = a * b;
    res2 = c * d;
    return res2;
}

int func2(int res2)
{
    res2 = func1(res2);
    printf("%d", res2);
}

所以res2存储int值的结果,res1存储float值的结果。从上面的逻辑我能够传递res2(这是int)但不能传递res1的值(浮点数)。我不知道我在哪里错过了这一点。这该怎么做。请帮忙,谢谢。!

1 个答案:

答案 0 :(得分:0)

函数类型指示它返回的值的类型

// func1 returns values of type int
int func1(void) {
    // return 3.14169; // automagically convert to 3
    // return "pi";    // error: cannot convert "pi" to a value of type int
    return 42;
}

如果希望函数返回浮点类型的值,则需要使用浮点类型定义它们

// func3 returns a floating point value of type double
double func3(void) {
    // return 3.14159 // return the value
    // return "pi";   // error: cannot convert "pi" to a value of type double
    return 42;        // converts the int value to the same value in type double
}