In the following code of mine, the modulo operator is used on two randomly generated numbers but the output is often incorrect. Why would that happen?
Here's an example of unexpected output:
#include <stdio.h>
#include <windows.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
void delay(int number_of_seconds)
{
// Converting time into milli_seconds
int milli_seconds = 1000 * number_of_seconds;
// Storing start time
clock_t start_time = clock();
// looping till required time is not achieved
while (clock() < start_time + milli_seconds)
;
}
void ran_dom(){ //this function generates a random number and prints its remainder
srand(time(0));
int x = (int) rand();
int y = (int) rand();
printf("x: %d\n", x);
printf("y: %d\n", y);
int mod_x = (x % 40); //modulo operator with value: 40
int mod_y = (y % 20); //modulo operator with value: 20
printf("x mod 40: %d\n", mod_x);
printf("y mod 20: %d\n", mod_y);
}
void ResetScreenPosition(){ //resets screen position (in windows OS)
COORD Position;
HANDLE hOut;
hOut = GetStdHandle(STD_OUTPUT_HANDLE);
Position.X = 0;
Position.Y = 0;
SetConsoleCursorPosition(hOut, Position);
}
void main(){
while(1){
ResetScreenPosition();
ran_dom();
delay(2);
}
}
Thanks for taking a look!
Aucun commentaire:
Enregistrer un commentaire