错误:C中'pow'的类型冲突

时间:2014-01-06 16:31:35

标签: c function conflict pow

该程序应该从用户获取大写和小写字母,并将每个字母分配给一个值。

实施例。 S为0,K为1,E为2 总值公式为((A * 10)+(B))* 10 ^ C

A - 第一个输入B - 第二个输入C是第3个输入 函数int lettervalue(char letter)应该返回字母的值。 我使用switch构造来分配字母值。

每次我编译我得到error: conflicting types for 'pow'。 pow函数是否接受变量,是否应该在函数int lettervalue(char letter)中更改?

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

int pow(int x, int y);

int lettervalue(char letter)
{
    int val;
    switch (letter){
        case 'S':
        case 's':
            val = 0;
            break;
        case 'K':
        case 'k':
            val = 1;
            break;
        case 'E':
        case 'e':
            val =2;
            break;
    }
    return val;
}

int main(void)
{   int valueA, valueB, valueC, totalvalue;
    char A, B, C;
    printf("Please input the letter: ");
    scanf("%c%c%c", &A, &B, &C);                
    valueA = lettervalue(A)*10;
    valueB = lettervalue(B);
    valueC = lettervalue(C);
    totalvalue = (valueA+valueB)*pow(10, valueC);
    printf("The total value is %d", totalvalue );

    return 0;
}

3 个答案:

答案 0 :(得分:2)

代码不必要地提供pow()原型,与math.h中的原型不一致。

#include <math.h>
// math.h provides: double pow(double x, double y);

消除int pow(int x, int y);

更改代码

// totalvalue = (valueA+valueB)*pow(10, valueC);
totalvalue = (valueA+valueB)* ((int)pow(10, valueC));

或者

double total;
total = (valueA+valueB)*pow(10, valueC);
printf("The total value is %.0lf", total );

请务必在数学库中链接以避免'未定义对pow的引用'。

"undefined reference to `pow'" even with math.h and the library link -lm

答案 1 :(得分:1)

如果你已经使用math.h,则不需要声明函数pow。因此,删除行int pow(int x,int y);应该有所帮助。

如果你想创建自己的简单pow函数,你不需要添加库math.h,并按如下方式定义函数pow:

int pow(int x, int y)
{
  int result=1,i;
  for(i=1;i<=y;i++)
    result *=x;

  return result;
}

p / s:由于pow功能增长很快,我建议您使用long值代替int

答案 2 :(得分:1)

pow()函数在math.h中定义为:

double pow (double base, double exponent);

用于pow()的原型会在您将参数类型更改为int时在参数类型之间产生冲突。您无法以这种方式更改输入和输出类型。你只需通过转换参数和返回的值来实现它,但这不是必要的,因为转换是隐式完成的。

只需移除pow()原型。