2015-10-05 54 views
0

使用函數原型創建程序時,出現了問題。它說:錯誤:語義問題從不兼容類型'void'分配'int'

Semantic issue Assigning to 'int' from incompatible type 'void'. 

能否請你幫我解決這個問題?

這裏是我的代碼:

#include <stdio.h> 
#include <math.h> 

void powr(int); 

int main(void) { 

    int n=1, sq, cu, quart, quint; 

    printf("Integer Square Cube Quartic Quintic\n"); 

    do { 

     sq = powr(n); //here is the error line 
     cu = powr(n); //here is the error line 
     quart = powr(n); //here is the error line 
     quint = powr(n); //here is the error line 
     printf("%d %d %d %d %d\n", n, sq, cu, quart, quint); 
     n++; 
    } 
    while (n<=25); 

    return 0; 
} 

void powr(int n) 
{ 
    int a, cu, quart, quint; 

    a=pow(n,2); 
    cu=pow(n,3); 
    quart=pow(n,4); 
    quint=pow(n,2); 
} 
+1

'powr'被定義爲void,如果你想以這種方式使用它,原型應該是'int powr(int n)' – amdixon

+0

@amdixon和下一個4個返回值的問題。 :) –

+0

不知道用戶在這裏做什麼。真的應該使用像sq = pow(n,2); ... quint = pow(n,5)這樣的std數學函數pow。 – amdixon

回答

3
void powr(int n) 

意味着該函數將返回什麼,所以你不能這樣做:

sq = powr(n); 

如果你想您的功能採取int返回int,它應該是:

int powr(int n) 

(用於原型和函數定義)。


在任何情況下,您設置powr功能不可用給調用者(和使用全局變量是在一般一個非常糟糕的主意),所以你需要更改的函數變量回到剛纔的平方數,因此稱之爲:

sq = powr (n); 
cu = n * sq; 
quart = powr (sq); 
quint = n * quart; 

或者你會傳遞變量到函數的地址,這樣他們就可以改變的,是這樣的:

void powr(int n, int *pSq, int *pCu, int *pTo4, int *pTo5) { 
    *pSq = pow (n, 2); 
    *pCu = *pSq * n; 
    *pTo4 = pow (*pSq, 2); 
    *pTo5 = *pCu * *pSq; 
} 

,並稱之爲:

powr (n, &sq, &cu, &quart, &quint); 

我建議使用前一種方法,因爲你出現在被學習的水平(事並無惡意,只是說,爲了幫助您選擇合適的方法)。

+0

謝謝,這真的很有幫助! –

+0

@БолатТлеубаев如果這個答案對您有幫助,並且能夠回答您的問題,請點擊答案左側的複選標記以接受答案。 – Keale

相關問題