[英]Calling a function in from main()
我刚刚开始学习 C,现在我发现如何从另一个调用 function 有点令人困惑。 这是我的小项目,我认为扭动“int result = timeToWork;”这一行调用 function 就足够了,但是会出现警告“从 'int(*)(int)' 初始化 'int' 使 integer 从没有强制转换的指针中获取”。 该项目编译,但结果是一些奇怪的数字而不是打印该行。 我究竟做错了什么?
#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;
}
function 有一个参数。
int timeToWork(int input);
那么如何在不向 function 传递参数的情况下调用它?
int result = timeToWork;
即使 function 不接受参数,您也必须在 function 设计器之后指定括号。
在上面的声明中 function 指示符只是转换为指向 function 的指针
看起来像
int( *fp )( int ) = timeToWork;
int result = fp;
要调用 function 你应该写
int result = timeToWork( key );
而不是
printf("Time = %d \n",timeToWork);
很明显你的意思是
printf("Time = %d \n", result);
虽然 function 定义不正确,因为它总是返回 0。
我认为 function 应该按以下方式声明和定义
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;
}
您的 function timeToWork
需要输入。
它应该是int result = timeTowork(key);
另外,这里要打印什么?: printf("Time = %d \n",timeToWork);
您需要发送 int 类型的参数,因为 function 期待它。
int result = timetowork(#your input goes here);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.