首页 > 解决方案 > C 模运算符在我的代码中随机生成的整数表现异常

问题描述

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

这是意外输出的示例:

#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);
    }
}

谢谢参观!

标签: crandom

解决方案


6327 % 407。如果屏幕在先前打印的 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);

推荐阅读