c中用户定义函数的冲突类型

很长一段时间后我在c工作。我必须实现三个function,包括

  1. 得到一个数字并显示一半

2.获取数字的平方

3.获取两个数字并显示它们的总和和消除。

我正在使用devC ++,当我编译代码时,我得到了我在标题中提到的错误, conflict type if squareInput这里有什么问题:

 #include #include int main(){ float x; printf("enter a number\n"); scanf("%f",&x); //TASK 1 : display half of the number pirntf("half of x is = %.3f",x); //TASK 2 : square of number squareInput(x); //call square function from here // TASK 3 : get two numbers and display both summation and sabtraction float num1,num2; // declare two floating number( floating numbers can hold decimal point numbers printf("enter num1 \n"); scanf("num1 is =%f",&num1); printf("enter num2 \n"); scanf("num2 is =%f",num2); calculate(num1,num2);// call calculate function getch(); } float squareInput(float input){ float square=input*input; printf("\n square of the number is %.3f \n",square); return 0; } float calculate(float num1,float num2){ //summation float summation= num1+num2; // declare antoher variable called summation to hold the sum //sabtraction float sabtraction=num1-num2; printf("summation is %.2f \n",summation); printf("sabtraction is %.2f \n",sabtraction); return 0; } 

没有原型就会出问题。 加

 float squareInput(float input); float calculate(float num1,float num2); 

int main()前面。

如果在调用函数之前没有声明函数,则编译器将其假定为int返回函数。 但是, squareInput()返回float,因此编译器(或者链接器)可能会向您抱怨。

另请注意,定义是声明(但反之亦然,显然),因此在调用它们的位置前移动squareInput()calculate()的定义也可以。

在调用squareInputcalculate ,它们尚未定义。 因此C假定int squareInput()int calculate()的隐式声明。 这些隐式声明与这些函数的定义冲突。

您可以通过在main之前为每个函数添加声明来解决此问题:

 float squareInput(float input); float calculate(float num1,float num2); 

或者只是在main之前简单地移动function。

使用函数时,请务必添加原型。 这样您就不必过多担心调用它们的顺序。

如果可以,也尝试将问题分成更小的位。 像TAKS1这样的评论向您显示您实际上想要一个具有该名称的函数。

 #include  //prototypes void AskUserForOneNumer(float * number, const char * question ); void TASK_1(float x); void TASK_2(float x); void TASK_3(float a, float b); int main() { float x, a, b; AskUserForOneNumer(&x, "enter x"); AskUserForOneNumer(&a, "enter a"); AskUserForOneNumer(&b, "enter b"); TASK_1(x); TASK_2(x); TASK_3(a, b); } void TASK_1(float x) { printf("x = %g\n", x); printf("0.5 * x = %g\n", 0.5 * x); } void TASK_2(float x) { printf("x = %g\n", x); printf("x * x = %g\n", x * x); } void TASK_3(float a, float b) { printf("a = %g\n", a); printf("b = %g\n", b); printf("a + b = %g\n", a + b); printf("a - b = %g\n", a - b); } void AskUserForOneNumer(float * number, const char * question) { float x; printf("%s\n", question); scanf("%f", &x); printf("your input was %g\n", x); *number = x; }