C 模运算符在我的代码中对随机生成的整数表现异常

标签 c random

在我的以下代码中,对两个随机生成的数字使用模运算符,但输出通常不正确。为什么会发生这种情况?

以下是意外输出的示例:

#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 % 407。如果屏幕上的 23 位于上次打印的 7 的位置,则打印 "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 模运算符在我的代码中对随机生成的整数表现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59719428/

相关文章:

你能帮助改进我大学的一门低级软件和外围接口(interface)类(class)吗?

swift - 代码是正确的,但有时我会遇到运行时错误

c++ - 有没有更快的方法从特定的数字池中获取随机数

java - 随机,与最后 10 个不同。(Java)

c - C 程序中的内存泄漏

c - 错误 : redifinition; different basic types

C 与 Ubuntu 上的 Eclipse : why is an . exe 并且没有创建 linux 可执行文件?

java - java随机类

java - 如何打乱数组的内容

c - make : *** [. o]错误1