[英]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.