[英]C modulo operator behaving unusually with randomly generated integer in my code
在我的以下代碼中,模運算符用於兩個隨機生成的數字,但輸出通常不正確。 為什么會這樣?
以下是意外輸出的示例:
#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);
}
}
謝謝參觀!
6327 % 40
是7
。 如果屏幕在之前打印的 7 的位置有 23,打印"x mod 40: 7"
將看起來打印了"x mod 40: 73"
。
嘗試按照以下替代方法之一進行操作:
printf("x mod 40: %02d \n", mod_x);
printf("[x mod 40: %d]\n", mod_x);
據我所知,在 c 中沒有清除屏幕的標准方法。 輸出中的錯誤來自覆蓋屏幕而不清除它。
在 unistd.h 中還有一個 sleep(int seconds) 函數。 使用它可能比循環更好。
調用 srand() 一次就足夠了。 您不需要在每次調用時設置隨機種子。
這可能是我的實現:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
void clear_screen() {
#ifdef WINDOWS
system("cls");
#else
/* Assume POSIX */
system ("clear");
#endif
}
void print_random() {
int x, y, mod_x, mod_y;
x = rand();
y = rand();
printf("x: %d\n", x);
printf("y: %d\n", y);
mod_x = (x % 40);
mod_y = (y % 20);
printf("x mod 40: %d\n", mod_x);
printf("y mod 20: %d\n", mod_y);
}
int main() {
srand(time(NULL));
while(1) {
clear_screen();
print_random();
sleep(2);
}
return 0;
}
由於我現在手頭沒有 Windows 機器,我只能在我的 Ubuntu 上測試此代碼。 雖然應該工作。
我剛剛發現在從 main 函數調用 delay() 之后放置這段代碼也有效:
system("cls"); // refreshes screen? works!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.