gpt4 book ai didi

c - 错误: incompatible types for a function that returns float in C

转载 作者:行者123 更新时间:2023-11-30 21:41:24 25 4
gpt4 key购买 nike

这是一个非常简单的代码,但我无法找出问题所在..

float fare;
fare = calculate_fare(stops);

float calculate_fare(int stops)
{
int stops_left = stops;
float fare = 10.0;
if (stops != 17)
{
stops_left = stops - 5;
while (stops_left>0)
{
fare += 5.0;
stops_left -= 5;
}
}
if (stops == 17)
{
fare = 20.0;
}

return fare;
}

我收到错误:“calculate_fare”的类型冲突之前对“calculate_fare”的隐式减速在这里

我已经尝试过返回 double 而不是 float,但它也不起作用。另外,尝试将 float 写为 10.0f ,即使这样也不起作用。还尝试对要返回的 float 进行类型转换。该程序确实有一个返回 int 的工作函数。在代码块上运行代码。任何帮助,将不胜感激。谢谢!

最佳答案

如果 C 编译器不知道函数签名,它会根据提供的参数推断输入参数,并将返回类型推断为 int

在第一次使用函数之前声明该函数:

float calculate_fare(int stops);

或者将整个定义放在翻译单元的顶部。

即错误:

[...] previous implicit declaration for 'calculate_fare' was here [...]
// ^^^^^^^^ ^^^^^^^^^^^

表明编译器之前没有对该函数进行声明,因此必须自己生成一个声明。

关于c - 错误: incompatible types for a function that returns float in C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25710971/

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