我正在做一个程序,其中我必须在其他函数中使用局部变量。如果变量数据类型为int,但能够浮动,则无法运行。

我正在使用下面的代码传递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的值(它是float)。我不知道我在哪里错过了重点。这该怎么做。请帮助,谢谢。

最佳答案

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

// 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
}

关于c - 如何将float变量从一个函数传递到另一函数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29715550/

10-11 23:10
查看更多