4.6 - מערכת - פתרון
הנה פתרון מלא לתרגיל “שעון עצר אקראי” עם הערות להסבר:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h> // for sleep on Linux
int main() {
// step 1: print the current time
time_t now = time(NULL);
printf("הזמן הנוכחי: %s", ctime(&now));
// step 2: draw a random number between 3 and 7
srand(time(NULL)); // seed the random number generator using the current time
int delay = rand() % 5 + 3; // random number between 3 and 7
// step 3: delay
printf("ממתין %d שניות...\n", delay);
sleep(delay); // delay
// step 4: print the new time
now = time(NULL);
printf("הזמן כעת: %s", ctime(&now));
// step 5: check an environment variable
if (getenv("DEBUG") != NULL) {
printf("מצב ניפוי פעיל\n");
}
// step 6: clear the screen (adapted per operating system)
#ifdef _WIN32
system("cls");
#else
system("clear");
#endif
// end of program
exit(0);
}