2017-05-19 13 views
-1

我是編程新手。所以,細節表示讚賞。編譯器顯示「作爲賦值左操作數所需的錯誤左值」。這是什麼意思,以及如何解決它?

#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; 
    } 
+0

http://code.geeksforgeeks.org/5x2pXV – rsp

+0

@rsp回答這個問題的評論應該是答案。僅編輯鏈接的答案應進行編輯以提供解釋,而不要求讀者對外訪問。 – Yunnosch

+0

如果你是新手,想要學習C語言,[**好書**](https://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list)將首先爲您服務,特別是作爲語法,語言細節和圖書館的參考。我懷疑你正在嘗試[做這樣的事情](http://ideone.com/mYEsD6),但你應該花費用來學習更多關於語言的知識並理解它的工作原理。 – WhozCraig

回答

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; 
} 
+0

@YunbinLiu的另一個答案顯示了一個沒有函數的乾淨方式,而是使用了一個變量。你自己的方式可能介於兩者之間。 – Yunnosch

+0

@SouravGHosh的回答解釋了爲什麼'float f(x);'的聲明不能提供錯誤和有用的附加信息。 – Yunnosch

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" 
+0

是的,但它仍然不是答案。 – roottraveller

+0

@rootTraveller是啊?請詳細說明一下? –

+0

@rootTraveller這是「這是什麼意思?」的答案。其他人選擇回答「如何解決它?」部分。這是一個很好的Q/AA三人組合。 – Yunnosch

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; 
} 
相關問題