gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:38:17 25 4
gpt4 key购买 nike

我正在编写一个程序,其中我必须在其他函数中使用局部变量。如果变量数据类型是 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com