2015-10-05 328 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

相关问题