`rand() % 2` 的意思是什么?

huangapple go评论141阅读模式
英文:

What does `rand() % 2` mean?

问题

rand() % 2 是一个条件表达式,它的作用是生成一个随机的0或1,用来确定是信用(credit)还是借记(debit)。如果 rand() % 2 的结果为1,就执行信用操作,否则执行借记操作。

英文:

I've come across this program but I can't seem to figure out this part. Please help me understand what is the use of rand() % 2 and how is it a condition to determine whether it's credit or debit?

#include<stdio.h>
#define NUM_TRANS 400
void * transactions(void * args) {
  int v;
	
  for(int i = 0; i < NUM_TRANS; i++) {
    v = (int) rand() % NUM_TRANS;
  
    if (rand() % 2) {
      // Crediting to user
      
     
      pthread_mutex_lock(&balance_lock);
      balance = balance + v;
      pthread_mutex_unlock(&balance_lock);
      
      pthread_mutex_lock(&credits_lock);
      credits = credits + v;
      pthread_mutex_unlock(&credits_lock);
      
    } else {
      // Debiting from user

      pthread_mutex_lock(&balance_lock);
      balance = balance - v;
      pthread_mutex_unlock(&balance_lock);
      
      pthread_mutex_lock(&debits_lock);
      debits = debits + v;
      pthread_mutex_unlock(&debits_lock);
    }
  }
}

答案1

得分: 3

rand() % 2 是一种生成伪随机数的方式,可以得到 0 或 1。

rand() 函数生成一个伪随机整数。当你将该整数对 2 取模(即 rand() % 2),实际上是在请求获取随机数除以 2 的余数。

由于任何数除以 2 都只有余数 0 或 1,所以 rand() % 2 总是得到 0 或 1。这相当于抛硬币,只有两种可能的结果。

在这个程序中,rand() % 2 用在一个 if 条件中,随机决定两种不同的操作:

如果 rand() % 2 评估为 1(或任何非零数,C 中视为 true),则程序会为用户添加一个伪随机值 v。

如果 rand() % 2 评估为 0(在 C 中视为 false),则程序会从用户中扣除伪随机值 v。

在这些操作周围使用互斥锁是为了确保没有其他线程可以在同一时间访问和修改余额、信用和借方变量,从而避免在多线程环境中出现竞态条件。

英文:

The rand() % 2 is a way of generating a pseudo-random number that's either 0 or 1.

The rand() function generates a pseudo-random integer. When you take the modulus of that integer by 2 (i.e., rand() % 2), you're essentially asking for the remainder of the division of the random number by 2.

Since any number divided by 2 has a remainder of either 0 or 1, rand() % 2 will always result in either 0 or 1. This is equivalent to flipping a coin where there are only two possible outcomes.

In this program, rand() % 2 is used in an if condition to randomly decide between two different operations:

If rand() % 2 evaluates to 1 (or any non-zero number, which is considered true in C), then the program credits a user with a pseudo-random value v.

If rand() % 2 evaluates to 0 (which is considered false in C), then the program debits a user with the pseudo-random value v.

The use of a mutex lock around these operations is to ensure that no other thread can access and modify the balance, credits, and debits variables at the same time, avoiding race conditions in a multithreaded context.

huangapple
  • 本文由 发表于 2023年6月13日 06:57:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76460777.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定