C++ 错误:表达式不能用作函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21617609/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:44:03  来源:igfitidea点击:

Error: expression cannot be used as a function?

c++compiler-errors

提问by LoreleiRS

I created a quick method in my program to compute the distance between two points using the distance formula, here's the code:

我在我的程序中创建了一个快速方法来使用距离公式计算两点之间的距离,代码如下:

#include <iostream>
#include <cmath>

using namespace std;

int distanceFormula(int x1, int y1, int x2, int y2) {
    double d = sqrt((x1-x2)^2(y1-y2)^2);
    return d;
}

it gives me a compiler error on the line where I declare the "d" variable saying that "error: expression cannot be used as a function". What does this mean? and what am I doing wrong?

它在我声明“d”变量的那一行给了我一个编译器错误,说“错误:表达式不能用作函数”。这是什么意思?我做错了什么?

回答by Mr_Pouet

Be careful, (x1-x2)^2will not do an exponent of 2 here. See http://www.cplusplus.com/reference/cmath/pow/.

小心,(x1-x2)^2这里不会做 2 的指数。请参阅http://www.cplusplus.com/reference/cmath/pow/

Second, you probably forgot a +in your expression:

其次,您可能+在表达式中忘记了 a :

int distanceFormula(int x1, int y1, int x2, int y2) {
    double d = sqrt(pow(x1-x2, 2) + pow(y1-y2, 2));
    return d;
}

回答by user2864740

The compiler error is because 2(y1-y2)is invalidsyntax.

编译器错误是因为2(y1-y2)无效的语法。

In this case 2(or perhaps (x1-x2)^2) is the "expression" and (y1-y2)is taken as a function call argument list; this grammar production is simply not allowed.

在这种情况下2(或者可能(x1-x2)^2)是“表达式”(y1-y2)并被视为函数调用参数列表;这种语法产生是根本不允许的。

Compare the following form where a binary operator (*) is introduced, which in turn makes the parser treat the subsequent (y1-y2)as an expression (bounded by grouping parenthesis) and not a function call. While it won't do what is desired, as ^is not exponentiation and the resulting equation is nonsense, it should parse and compile.

比较以下形式,其中*引入了二元运算符 ( ),这反过来使解析器将后续(y1-y2)表达式视为表达式(以分组括号为界)而不是函数调用。虽然它不会做预期的事情,因为^它不是求幂并且结果方程是无意义的,但它应该解析和编译。

sqrt((x1-x2)^2*(y1-y2)^2)