从main()调用函数

问题描述 投票:0回答:3

我刚刚开始学习C,现在我发现如何从另一个函数调用一个函数有些困惑。这是我的小项目,我认为将“ int result = timeToWork;”这一行写错了。足以调用该函数,但是出现警告“从'int(*)(int)'初始化'int'使指针的整数不进行强制转换”。项目可以编译,但是结果是一些奇怪的数字,而不是打印行。我在做什么错?

#include<stdio.h>
int timeToWork(int input);
int main()
{
    printf("Please, enter the number  \n");
    int key = 0;
    fflush(stdout);
    scanf("%d", &key);
    int result = timeToWork;
    printf("Time = %d  \n",timeToWork);

    return 0;
}
int timeToWork(int input)
{
    if(input == 1)printf("It will take you 25 minutes to get to your destination by car  \n");
    else if(input == 2)printf("It will take you 20 minutes to get to your destination by bike  \n");
    else if(input == 3)printf("It will take you 35 minutes to get to your destination by bus  \n");
    else if(input == 4)printf("It will take you 30 minutes to get to your destination by train  \n");
    else printf("ERROR: please, enter a number from 1 to 4  \n");

    return 0;
}
c function definition function-call
3个回答
3
投票

该函数具有一个参数。

int timeToWork(int input);

所以您如何在不将参数传递给函数的情况下调用它?

int result = timeToWork;

即使函数不接受参数,也必须在函数设计器之后指定括号。

在上面的函数指定符中的声明只是转换为指向函数的指针

看起来像

int( *fp )( int ) = timeToWork;
int result = fp;

调用您应该编写的函数

int result = timeToWork( key );

而不是

printf("Time = %d  \n",timeToWork);

很明显,您的意思是

printf("Time = %d  \n", result);

尽管函数定义不正确,因为它总是返回0。

我认为应该通过以下方式声明和定义函数

int timeToWork( int input )
{
    int time = 0;

    if(input == 1)
    {
        printf("It will take you 25 minutes to get to your destination by car  \n");
        time = 25;
    }
    else if(input == 2)
    {
        printf("It will take you 20 minutes to get to your destination by bike\n");
        time = 20;
    }
    else if(input == 3)
    {
        printf("It will take you 35 minutes to get to your destination by bus  \n");
        time = 35;
    }
    else if(input == 4)
    {
        printf("It will take you 30 minutes to get to your destination by train  \n");
        time = 30;
    }
    else
    {
         printf("ERROR: please, enter a number from 1 to 4  \n");
    }

    return time;
}

0
投票

您的功能timeToWork需要输入。

应为int result = timeTowork(key);

而且,这里要打印什么?:printf("Time = %d \n",timeToWork);


0
投票

您需要发送int类型的参数,因为函数需要它。

int result = timetowork(#your input goes here);
© www.soinside.com 2019 - 2024. All rights reserved.