繁体   English   中英

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

[英]confliction type for a user defined function in c

过了很长时间我在c中工作。在这里我必须实现三个功能,其中包括

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

2.获取数字的平方

3.得到两个数字并显示它们的总和和抽象。

我正在使用devC ++,当我编译代码时,我得到了我在标题中提到的错误,该错误是conflict type if squareInput

#include<stdio.h>
#include<conio.h>
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()的定义squareInput()它们被调用的位置也可以。

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

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

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

或者通过简单地将功能整体移至main之前。

使用函数时,请确保添加原型。 这样,您不必太担心您调用它们的顺序。

如果可以的话,也请尝试将问题分解为较小的部分。 像TAKS1这样的注释向您表明,您实际上需要具有该名称的功能。

#include <stdio.h>

//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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM