C语言 如何使用代码块 13.12(mingw) 在 c 中使用 delay() 函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27447195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use delay() function in c using codeblocks 13.12(mingw)?
提问by Sri Harsha
When I write a program containing delay the compiler shows the error E:\c programms\ma.o:ma.c|| undefined reference to `delay'| ||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
当我编写包含延迟的程序时,编译器显示错误 E:\c programms\ma.o:ma.c|| 对`delay'的未定义引用| ||=== 构建失败:1 个错误,0 个警告(0 分钟,0 秒)===|
回答by Armali
Try including windows.hand use Sleep(sleep_for_x_milliseconds)instead of delay()– Cool Guy
尝试包含windows.h并使用Sleep(sleep_for_x_milliseconds)代替delay()– Cool Guy
回答by Rizwan Raza
You can use your own created delay() function for delaying statements for milliseconds as passed in parameter...
您可以使用自己创建的 delay() 函数将语句延迟几毫秒作为参数传递...
Function Body is below.....
函数体如下.....
#include<time.h>
void delay(unsigned int mseconds)
{
clock_t goal = mseconds + clock();
while (goal > clock());
}
只需将上述代码粘贴到您的 C/C++ 源文件中...
example program is below...
示例程序如下...
#include<stdio.h>
#include<time.h>
void delay(unsigned int mseconds)
{
clock_t goal = mseconds + clock();
while (goal > clock());
}
int main()
{
int i;
for(i=0;i<10;i++)
{
delay(1000);
printf("This is delay function\n");
}
return 0;
}
回答by Abdulkader
Try this function:
试试这个功能:
#include <time.h> // clock_t, clock, CLOCKS_PER_SEC
void delay(unsigned int milliseconds){
clock_t start = clock();
while((clock() - start) * 1000 / CLOCKS_PER_SEC < milliseconds);
}
- The parameter milliseconds is a nonnegative number.
- clock() returns the number of clock ticks elapsed since an epoch related to the particular program execution.
- CLOCKS_PER_SEC this macro expands to an expression representing the number of clock ticks per second, where clock ticks are units of time of a constant but system-specific length, as those returned by function clock.
- 参数毫秒是一个非负数。
- clock() 返回自与特定程序执行相关的纪元以来经过的时钟滴答数。
- CLOCKS_PER_SEC 此宏扩展为表示每秒时钟滴答数的表达式,其中时钟滴答是恒定但系统特定长度的时间单位,如函数 clock 返回的那些。

