编译器显示"error lvalue required as left operand of assignment" .这是什么意思以及如何解决它?



我是编程新手。因此,细节值得赞赏。

#include<stdio.h>
#include<math.h>
int main()
{
float x, f(x);
printf("Enter x=");
scanf("%f", &x);
f(x)= 3*pow(x, 5)- 5*sqrt(x)-6*sin(x); /*in this line compiler shows error*/
printf("f(x)= %f", f(x));
return 0;
}

请原谅我假设您是 C 初学者,正在寻找用 C 编写函数的方法。那里有很多 C 教程,我建议找一个进一步学习。
下面是使用实际 C 函数执行的操作的示例。

#include<stdio.h>
#include<math.h>
/* first define the function */
float f(float x) /* function head */
{ /* start of function body */
return  3*pow(x, 5) - 5*sqrt(x)-6*sin(x);
} /* end of function body and definition */
int main(void)
{
float x; /* definition of function has already happened, so no f(x) here */
printf("Enter x=");
scanf("%f", &x);
printf("f(x)= %f", f(x) /* call the function */);
/* Note that some coding styles do not like calling a function 
from within a more complex statement. Using a variable to
take the result of the function is preferred.  
I chose this way to stay more similar to your own code.
*/
return 0;
}

以下方法可能有效。

#include <stdio.h>
#include <math.h>
int main()
{
float x, f;
printf("Enter x=");
scanf("%f", &x);
f = 3 * pow(x, 5) - 5 * sqrt(x) - 6 * sin(x);
printf("f(x)= %f", f);
return 0;
}

在代码中,f(x)是有效的标识符,但不是变量。这是一个写得很差(根据最新的 C 标准现在无效)函数原型。您不能分配给它,它不是一个可修改的左值。

这就是为什么在

f(x)= 3*pow(x, 5)- 5*sqrt(x)-6*sin(x);

编译器尖叫。


关于为什么您的代码没有为无效格式抛出错误,这是编译器中的遗留支持。在您的情况下

float x, f(x);

被视为

float x, float f ( int x ) ;  //missing data type is treated as 'int', 
// DON'T rely on this "feature"

最新更新