Home > Back-end >  How do I printf a phrase on a certain probability?
How do I printf a phrase on a certain probability?

Time:11-20

So I’m trying to create a buy and sell program and in there, I also coded the range where a random price out of a certain range will pop out. Now the problem is I can’t figure out a way on how to display a “not available today” on a 15% chance. so basically the price list will only show the price of the item OR a “not available today” note.

this is how the code looks like now. i only inserted the price range and an srand function.


srand(time(NULL));
item1 = rand() % (1000 - 500   1)   500;
item2 = rand() % (5000 - 1500   1)   1500;
item3 = rand() % ( 8000 - 5000   1 )   5000;

  printf("The Price of Item1 is %dG\n", item1);
  printf("The Price of Item2 is %dG\n", item2);
  printf("The Price of Item3 is %dG\n", item3);
  

CodePudding user response:

if(rand() % 100 > 15)
{
    /* more than 15 */
}
else
{
    /* less or equal 15 */
}

CodePudding user response:

if ((rand()%(100) 1) <= 15 ) {
    printf("Item not available today\n");
} else {
    printf("The Price of Item1 is %dG\n", item1);
}

Could this be a simple implementation of what you are trying to do?

Edit: fixed rand()

  • Related