C 从main()调用中的函数
我刚刚开始学习C,现在我发现如何从一个函数调用另一个函数有点困惑。这是我的小项目,我认为写int result=timeToWork;调用该函数就足够了,但是从“int*int”初始化“int”时会出现警告,即从指针初始化整数而不进行强制转换。项目进行编译,但结果是一些奇怪的数字,而不是打印行。我做错了什么C 从main()调用中的函数,c,function,definition,function-call,C,Function,Definition,Function Call,我刚刚开始学习C,现在我发现如何从一个函数调用另一个函数有点困惑。这是我的小项目,我认为写int result=timeToWork;调用该函数就足够了,但是从“int*int”初始化“int”时会出现警告,即从指针初始化整数而不进行强制转换。项目进行编译,但结果是一些奇怪的数字,而不是打印行。我做错了什么 #include<stdio.h> int timeToWork(int input); int main() { printf("Please, enter the n
#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;
}
该函数有一个参数
int timeToWork(int input);
那么,在不向函数传递参数的情况下,如何调用它呢
int result = timeToWork;
即使函数不接受参数,也必须在函数deisgnator之后指定括号
在上面的声明中,函数指示符只是转换为指向函数的指针
看起来像
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;
}
您需要发送int类型的参数,因为函数需要它
int result = timetowork(#your input goes here);
函数timeToWork需要一个输入
它应该是int result=timeToworkkey
还有,你想在这里打印什么
printfTime=%d\n,timeToWork 我刚刚开始学习C语言-你在学习中使用了哪些资源?这些资源是否涵盖了如何调用函数?如果是,请说明他们说了什么以及为什么你不清楚。如果没有,也许您应该关注资源,直到它出现。对于这些非常基本的事情,,从培训资源中学习可能比试图从堆栈溢出中拼凑答案要好。无论您从哪个来源学习C,都应该有一个关于调用函数的部分-为什么不参考这个部分呢?您可能希望实际调用函数:int result=timeToWorkkey。您应该像在初学者C课本或任何你学习C的资源。这一点非常重要。顺便说一句:“int*int”中的“int”的警告初始化使得指针中的整数没有强制转换,这几乎总是一个错误。如果不是所有警告,那么大多数其他警告都应该被视为错误。第一句话听起来有点像int result=timeToWork;如果timeToWork不需要参数,则可以。也许你想澄清一下,时间=输入*5+20如何,它需要%d分钟,如果unsignedInput-1