c - 如何将浮点变量从一个函数传递到另一个函数?

标签 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 (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 - 如何将浮点变量从一个函数传递到另一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29715550/

相关文章:

javascript - 本地 Javascript 中的 SQLite 数据库

c - 十进制转二进制

iphone - Objective-c:在数组内分配变量而不是字符串

C语言关于前置自增和后置自增的策略

c++ - 变量名中的美元符号?

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

python - 写入 locals() 的工作方式与说明它不是的文档相反

sql - PL/SQL 脚本中的本地函数

c - 如何使用 printf 格式化 unsigned long long int?

c - FILE* 读取超时