gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 18:23:14 25 4
gpt4 key购买 nike

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

以下是意外输出的示例:

#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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com