错误:在"{"标记之前预期"",""或";"和"不能用作函数"

error: expected ',' or ';' before '{' token" and "cannot be used as a function

本文关键字:函数 不能 错误      更新时间:2023-10-16

我正在用C++编写一个从意大利里拉到欧元的转换器:

#include <iostream>
using namespace std;
float x;
int converter (x)
{
    y = x/1936,27;
    return y;
}
int main() 
{
    cout << "Give me the value: ";
    cin >> x;
    converter (x);
}

我试图编译它,但我看到两个错误。第一个是:

lire-euro.cpp:8: error: expected ‘,’ or ‘;’ before ‘{’ token

我在括号前定义了一个函数。为什么我应该把','';'放在'{'之前?第二个是:

lire-euro.cpp: In function ‘int main()’:
lire-euro.cpp:17: error: ‘converter’ cannot be used as a function

为什么我不能使用converter作为函数?这与另一个错误有关吗?

您的函数参数列表缺少参数类型:

int converter (float x) { ...
//             ^^^^^

除此之外,在函数的主体中,您使用未声明的y。您可以通过返回表达式来解决此问题,但可能需要将浮点文字中的,替换为.,具体取决于您的语言环境。

return x/1936.27;

请注意,返回浮点数可能比返回int更有意义。

最后,我认为x没有理由是全球性的。您可以在main():中声明

#include <iostream>
int converter(float x)
{
    return x/1936.27;
}
int main() 
{
    float x;
    std::cout << "Give me the value: ";
    std::cin >> x;
    int z = converter(x);
}

函数定义中有两个错误。首先,它的参数x没有类型说明符,它的局部变量y也没有定义。

我想你是指

float x;
int converter()
{
    int y = x/1936,27;
    return y;
}

虽然我不确定y(和函数返回类型)是否应该定义为int.

函数的相应调用可能看起来像

cout << converter() << endl;