如何在给定时间内使用 C 中的 while 循环 运行

how to run in a given time using while loop in C

这是给定的条件,我在设置时间间隔时遇到问题

在 5 分钟内从 2 中找出质数:

include <time.h>

end= start = (unsigned)time(NULL);

while((end-start)<300)

求素数

打印质数以及有多少个质数(频率)

end = (unsigned)time(NULL);

打印总执行时间

这是我做的代码。

#include <stdio.h> 
#include <time.h> 

int main()
{   
time_t end, start;
    
end = start = (unsigned)time(NULL);
int i, j;
int freq = 0;
int count = 0;

while ((end-start) < 300) {
    for (i = 2;; i++) {
        for (j = 2; j < i; j++) {
            if (i % j == 0) {
                count = 1;
                break;
            }
        }
        if (!count) {
            ++freq;
        }
        count = 0;
    }
    return i, freq;
    printf("Prime number: %d, frequency: %d\n", i, freq);
}
end = (unsigned)time(NULL);
printf("total time : %d seconds\n", end);

return 0;

}

我检查了发现质数部分,当我这样写时频率部分没问题`

        }
        count = 0;
        printf("Prime number: %d, frequency: %d\n", i, freq);

    }
    return i, freq;`

但是过了5分钟还是没有结果

根据 endstart 的值 5 分钟后,您的 while 循环结束。它们使用相同的值进行初始化。

endnever 在循环内更新,所以这将是一个无限循环。在 循环之后更新 end ,但为时已晚。您需要在每一步更新它,例如:

while ((end-start) < 300) {
    for (i = 2;(end-start) < 300; i++) {
        for (j = 2; j < i; j++) {
            if (i % j == 0) {
                count = 1;
                break;
            }
        }
        if (!count) {
            ++freq;
        }
        count = 0;
        end = (unsigned)time(NULL);    printf("Prime number: %d, frequency: %d\n", i, freq);
    }
    //Don't return at this point
    //return i, freq;
}